Colors

Denis S. Otkidach ods at fep.ru
Fri Aug 23 05:47:23 EDT 2002


On Thu, 22 Aug 2002, Juza wrote:

J> What's the instruction or module for print colored strings?

If you mean ANSI terminal than it's simple:


#!/usr/bin/env python


def colored(s, *opts):

    seq = {
        'clear'     : '0',
        'reset'     : '0',
        'bold'      : '1',
        'underline' : '4',
        'underscore': '4',
        'blink'     : '5',
        'reverse'   : '7',
        'concealed' : '8',

        'black'  : '30', 'on_black'   : '40',
        'red'    : '31', 'on_red'     : '41',
        'green'  : '32', 'on_green'   : '42',
        'yellow' : '33', 'on_yellow'  : '43',
        'blue'   : '34', 'on_blue'    : '44',
        'magenta': '35', 'on_magenta' : '45',
        'cyan'   : '36', 'on_cyan'    : '46',
        'white'  : '37', 'on_white'   : '47'
    }

    esc = '\x1b['
    sep = ';'
    end = 'm'

    if len(opts):
        seqs = []
        for opt in opts:
            seqs.append(seq[opt])
        return esc + sep.join(seqs) + end + s + esc + seq['reset'] + end
    else:
        return s

if __name__=='__main__':
    print colored('Test yellow blink bold on blue reverse', 'yellow', 'bold',
                  'on_blue', 'blink', 'reverse')

-- 
Denis S. Otkidach
http://www.python.ru/      [ru]
http://diveinto.python.ru/ [ru]





More information about the Python-list mailing list