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

Pearu Peterson pearu at cens.ioc.ee
Mon May 20 06:35:00 EDT 2002


Hi,

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?

Thanks,
	Pearu






More information about the Python-list mailing list