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

sorin picture sorin · Sep 16, 2011 · Viewed 10.9k times · Source

In order to detect if console, correctly sys.stderr or sys.stdout, I was doing the following test:

if hasattr(sys.stderr, "isatty") and sys.stderr.isatty():
   if platform.system()=='Windows':
       # win code (ANSI not supported but there are alternatives)
   else:
       # use ANSI escapes
else:
   # no colors, usually this is when you redirect the output to a file

Now the problem became more complex while running this Python code via an IDE (like PyCharm). Recently PyCharm added support for ANSI, but the first test fails: it has the isatty attribute but it is set to False.

I want to modify the logic so it will properly detect if the output supports ANSI coloring. One requirement is that under no circumstance I should output something out when the output is redirected to a file (for console it would be acceptable).

Update

Added more complex ANSI test script at https://gist.github.com/1316877

Answer

Taha Jahangir picture Taha Jahangir · Mar 7, 2014

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