ANSI colored output: How to determine how python was called?

Donn Cave donn at u.washington.edu
Mon May 20 12:19:33 EDT 2002


Quoth Pearu Peterson <pearu at cens.ioc.ee>:

| In my python program I want to output ANSI colored text only if the
| terminal where the program was executed can support ANSI colored text. In
| all other cases the program should output ordinary text.
|
| My initial approach was to check the TERM environment variable, for
| example,
|
| if os.environ.get('TERM',None) in ['rxvt','xterm']:
|     print '\x1b[31mHello!\x1b[0m' # red Hello!
| else:
|     print 'Hello!'
|
| But then I found that when this program is called through
|
|     commands.getstatusoutput(..)
|
| and its friends, then the above test fails in the sense that red `Hello!'
| is printed but I would like to have here an ordinary `Hello!'.
|
| So, my question is: 
|
|   Are there alternative (hopefully better) ways to decide whether the
|   output "device" of python stdout supports ANSI colored text or not?

The problem you encountered with commands.getstatusoutput() is
easily solved -

   if sys.stdout.isatty() and os.environ.get(...

As for the other problem, you'll never account for all the color
terminal emulators that way - many of them will show up as vt102,
or who knows what.  The original "xterm" was not color capable.
It might be nice to pull something else out of the environment too,
for the sake of people who are missing the boat on TERM - maybe
LS_COLORS, which is already used by GNU ls, or something specific
to your application.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list