ANSI colored output: How to determine how python was called?
David M. Cooke
cookedm+news at physics.mcmaster.ca
Tue May 21 14:47:42 EDT 2002
At some point, Pearu Peterson <pearu at cens.ioc.ee> 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?
>>
>> 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.
I think what you want is something like:
def term_has_colours():
if not sys.stdout.isatty():
return 0
curses.start_color()
return curses.has_colors()
curses.wrapper does more than you need. I use something like the above
in my $PYTHONSTARTUP file to give me a coloured prompt.
--
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
More information about the Python-list
mailing list