5 color_names
= ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
6 foreground
= dict([(color_names
[x
], '3%s' % x
) for x
in range(8)])
7 background
= dict([(color_names
[x
], '4%s' % x
) for x
in range(8)])
11 opt_dict
= {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'}
13 def colorize(text
='', opts
=(), **kwargs
):
15 Returns your text, enclosed in ANSI graphics codes.
17 Depends on the keyword arguments 'fg' and 'bg', and the contents of
20 Returns the RESET code if no parameters are given.
23 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
31 'noreset' - string will not be auto-terminated with the RESET code
34 colorize('hello', fg='red', bg='blue', opts=('blink',))
36 colorize('goodbye', opts=('underscore',))
37 print colorize('first line', fg='red', opts=('noreset',))
38 print 'this should be red too'
39 print colorize('and so should this')
40 print 'this should not be red'
44 if text
== '' and len(opts
) == 1 and opts
[0] == 'reset':
45 return '\x1b[%sm' % RESET
46 for k
, v
in kwargs
.iteritems():
48 code_list
.append(foreground
[v
])
50 code_list
.append(background
[v
])
53 code_list
.append(opt_dict
[o
])
54 if 'noreset' not in opts
:
55 text
= text
+ '\x1b[%sm' % RESET
56 return ('\x1b[%sm' % ';'.join(code_list
)) + text
58 def make_style(opts
=(), **kwargs
):
60 Returns a function with default parameters for colorize()
63 bold_red = make_style(opts=('bold',), fg='red')
64 print bold_red('hello')
65 KEYWORD = make_style(fg='yellow')
66 COMMENT = make_style(fg='blue', opts=('bold',))
68 return lambda text
: colorize(text
, opts
, **kwargs
)