Printing with colors in a portable way

Jan Kaliszewski zuo at chopin.edu.pl
Thu Jul 30 19:54:20 EDT 2009


31-07-2009 o 01:29:50 Rhodri James <rhodri at wildebst.demon.co.uk> wrote:

> On Thu, 30 Jul 2009 23:40:37 +0100, Robert Dailey <rcdailey at gmail.com>  
> 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).
>
> ...in an xterm, over a telnet connection, via VNC...
>
> There's no portable way of doing this in any language, since it's
> up to the terminal emulator exactly what it does with what incoming
> bytes.  Some respect the ANSI colour codes, some don't; that's about
> all that you can say.

Yeah. Although you could try to provide "term-sensitive" mapping
of colour names -> codes, e.g.:

# color_codes.py

class NoColors:
     blue = ''
     red = ''

class XtermColors:
     blue = '<a code here>'
     red = '<a code here>'

class FooBarColors:
     blue = '<a code here>'
     red = '<a code here>'

COLORS = {
     'nocolors': NoColors,
     'xterm': XtermColors,
     'another term': FooBarColors,
}


# a_program.py

import color_codes

# e.g. with used_term == 'xterm'...
colors = color_codes.COLORS[used_term]

print('Some text, {colors.blue}Something in blue, '
       '{colors.red}And now in red.').format(colors=colors)


Regards,
*j

-- 
Jan Kaliszewski (zuo) <zuo at chopin.edu.pl>



More information about the Python-list mailing list