Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 675
sorin Avatar asked Sep 16 '11 13:09

sorin


People also ask

How do you use ANSI escape code in Python?

The \033 is the escape code, just like a \n or \r , but this is sending a hex value through to the terminal. 01:07 The left square bracket ( [ ) is a parameter, {code} will be the code we're displaying, which I'm going to pass in through the function, and then the m tells ANSI that it's done.


1 Answers

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

like image 52
Taha Jahangir Avatar answered Oct 06 '22 13:10

Taha Jahangir