Printing with colors in a portable way

Nobody nobody at nowhere.com
Fri Jul 31 14:22:33 EDT 2009


On Thu, 30 Jul 2009 15:40:37 -0700, Robert Dailey wrote:

> Anyone know of a way to print text in Python 3.1 with colors in a
> portable way? In other words, I should be able to do something like
> this:
> 
> print_color( "This is my text", COLOR_BLUE )
> 
> And this should be portable (i.e. it should work on Linux, Mac,
> Windows).

The way that terminals (and emulators) handle colour is fundamentally
different from the DOS/Windows console. If you want something which will
work on both, you will have write separate implementations for terminals
and the DOS/Windows console.

For terminals, you can use the "curses" package, e.g.:

import curses

curses.setupterm()
setaf = curses.tigetstr('setaf')
setab = curses.tigetstr('setab')

def foreground(num):
    if setaf:
        sys.stdout.write(curses.tparm(setaf, num))

def background(num):
    if setab:
        sys.stdout.write(curses.tparm(setab, num))

For the Windows console, you'll need to use ctypes to interface to the
SetConsoleTextAttribute() function from Kernel32.dll.




More information about the Python-list mailing list