Nobody wrote:
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.


FYI

http://github.com/jbowes/markymark/blob/59511b36a752b40243cc18fb0fb9800c74549ac1/markymark.py

If the URL ever becomes invalid, then google for markymark.py
You can use it either to color your Linux/Unix terms, or you can just look at the python code to see how to set colors and attributes.


JM
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to