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

Geoff Gerrietts geoff at gerrietts.net
Mon May 20 20:45:10 EDT 2002


Quoting Pearu Peterson (pearu at cens.ioc.ee):
> 
> 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 way I've done this is something of a hack, but it's been a hack
that has worked for me. My understanding is that it's fairly portable
to Unix systems, but it doesn't port at all to non-unix systems, and I
can't vouch personally for how well it ports. It works well for me
under Linux.

The solution (if you can call it that, "ugly hack" might be more apt)
is to use the tput utility and let the terminal handling libraries
figure this stuff out for me. I liked this solution better than going
with curses.

Here's the test program I wrote when figuring all this crap out:

  import os

  # 0 black ; 1 red ; 2 green ; 3 yellow ; 4 blue ; 5 magenta ; 6 cyan ; 7 white

  NUMCOL  = os.popen("tput colors 2>/dev/null", "r").read()
  SAVE_C  = os.popen("tput sc 2>/dev/null", "r").read()
  RESETC  = os.popen("tput rc 2>/dev/null", "r").read()
  YEL_FG  = os.popen("tput setaf 3 2>/dev/null", "r").read()
  BLK_BG  = os.popen("tput setb 0 2>/dev/null", "r").read()
  NORMAL  = os.popen("tput sgr0 2>/dev/null", "r").read()
  BOLD    = os.popen("tput bold 2>/dev/null", "r").read()

  print NUMCOL
  print BLK_BG, YEL_FG, "wassup", BOLD, "hoser", NORMAL

If I'm remembering right, NUMCOL is set to 2 on a terminal that only
supports monochrome.

Discussion on this topic is plentiful across the net, but really solid
sources are hard to find. I wish I had the URLs for you, but I can
tell you that the best sources I've found have been in mailing list
threads where people are trying to get colour into their highly
customized prompt strings.

Sad, but true: in Linux as in Windows, the dominant force driving
technological discovery is making the desktop "look cool". :)

Best of luck,
--G.

-- 
Geoff Gerrietts           "By doing just a little every day, I can gradually 
                           let the task completely overwhelm me." 
<geoff at gerrietts net>        --Ashleigh Brilliant





More information about the Python-list mailing list