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

Pearu Peterson pearu at cens.ioc.ee
Mon May 20 18:15:30 EDT 2002


On 20 May 2002, François Pinard wrote:

> [Donn Cave]
> 
> > Quoth Pearu Peterson <pearu at cens.ioc.ee>:
> 
> > |   Are there alternative (hopefully better) ways to decide whether the
> > |   output "device" of python stdout supports ANSI colored text or not?
> 
> > 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.
> 
> The normal way to check for colour terminal support is through terminal
> info capabilities (terminfo).  Check for `op', 'AF', `AB', `Sf', `Sb',
> 'Co', `pa' and `NC' capabilities, in particular.  I forgot details as of
> now, but remember I had to fight a bit to get everything right.

Thanks for the hint.

I now discovered the Python curses module. It seems that

  sys.stdout.isatty() and curses.wrapper(lambda s:curses.has_colors())

gives a reliable answer for if the terminal supports colors or not.
However, when using it, the screen "blinks" (the terminal is blanked
and then its contents is restored) as curses.wrapper(..) initializes and
deinitializes the ncurses library. I have not found yet if this
"blink" could be avoided.

Pearu






More information about the Python-list mailing list