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

Michael Hudson mwh at python.net
Wed May 22 06:06:47 EDT 2002


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

> On 21 May 2002, David M. Cooke wrote:
> 
> > 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.
> 
> The problem with the above is that it also needs
> 
>   curses.initscr()

Hmm, has_colors() should probably require that you have called at
least setupterm(), not the full initscr().  Would be easy enough to
change.

> that in my python prompt messed up the terminal completely so that I have
> to blindly exit python and reset the terminal. And
> 
>   curses.endwin()
> 
> did not fixed the mess up either.
> 
> That's the reason why I ended up with using curses.wrapper that returns
> with properly restoring the current terminal.

Here's a version of has_colors() that only requires you call
setupterm() (newly supported in 2.2):

def has_colors_():
    return (curses.tigetnum("colors") >= 0
            and curses.tigetnum("pairs") >= 0
            and ((curses.tigetstr("setf") is not None 
                  and curses.tigetstr("setb") is not None) 
                or (curses.tigetstr("setaf") is not None
                    and curses.tigetstr("setab") is not None)
                or curses.tigetstr("scp") is not None))
            
It's just a translation of has_colors() from the ncurses source.

Cheers,
M.

-- 
  First time I've gotten a programming job that required a drug
  test.  I was worried they were going to say "you don't have
  enough LSD in your system to do Unix programming".   -- Paul Tomblin
               -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html



More information about the Python-list mailing list