Great for deciding automatically whether to use colors.
Based on http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116
1 2 3 4 5 6 7 8 9 10 11 12 13 | def has_colors(stream):
if not hasattr(stream, "isatty"):
return False
if not stream.isatty():
return False # auto color only on TTYs
try:
import curses
curses.setupterm()
return curses.tigetnum("colors") > 2
except:
# guess false in case of error
return False
|
Demonstration: <pre> import sys print has_colors(sys.stderr) </pre> A console program that supports color can decide automatically whether to use colors. The function returns false if the terminal doesn't support colors, or if the output is piped or redirected.
Based on http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116
which shows, among other stuff, how to get terminfo variables on the terminal.
Used in Testoob, http://testoob.sourceforge.net