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

Pearu Peterson pearu at cens.ioc.ee
Mon May 20 15:42:29 EDT 2002


On 20 May 2002, Donn Cave wrote:

> 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(...

Thanks!

> 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.

In debian woody and Suse linux only TERM and COLORTERM are defined by
default that I found to be related variables to this coloring issue.
And COLORTERM seems to be interpreted differently in these two linux
systems: in woody I have COLORTERM=rxvt while in Suse COLORTERM=1.

I checked that colorgcc is more liberal on coloring output than I
with TERM in [rxvt,xterm]. So, I think, I'll keep it in that way until
some old HP user will complain about the junk in its terminal ;)

Pearu






More information about the Python-list mailing list