How to detect if the console does support ANSI escape codes in Python?

Django users can use django.core.management.color.supports_color function.

if supports_color():
    ...

The code they use is:

def supports_color():
    """
    Returns True if the running system's terminal supports color, and False
    otherwise.
    """
    plat = sys.platform
    supported_platform = plat != 'Pocket PC' and (plat != 'win32' or
                                                  'ANSICON' in os.environ)
    # isatty is not always implemented, #6223.
    is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
    return supported_platform and is_a_tty

See https://github.com/django/django/blob/master/django/core/management/color.py

Leave a Comment