6 # Define ANSI escape sequences for colors
8 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
13 def standard_colors(use_color=None):
14 """Return a list of standard colors
16 >>> highlight,lowlight,good,bad = standard_colors()
17 >>> (highlight,lowlight,good,bad)
18 (None, 'blue', 'green', 'red')
28 highlight = lowlight = good = bad = None
29 return (highlight, lowlight, good, bad)
31 def _ansi_color_code(color):
32 r"""Return the appropriate ANSI escape sequence for `color`
34 >>> _ansi_color_code('blue')
36 >>> _ansi_color_code(None)
41 return '\033[3%dm' % (_COLORS.index(color))
43 def color_string(string, color=None):
44 r"""Wrap a string in ANSI escape sequences for coloring
46 >>> color_string('Hello world', 'red')
47 '\x1b[31mHello world\x1b[0m'
48 >>> color_string('Hello world', None)
51 It also works with non-unicode input:
53 >>> color_string('Hello world', 'red')
54 '\x1b[31mHello world\x1b[0m'
58 ret.append(_ansi_color_code(color))
61 ret.append(_ansi_color_code(None))
63 if isinstance(string, str): # i.e., not unicode
64 ret = [str(x) for x in ret]
68 def write_color(string, color=None, stream=None):
69 r"""Write a colored `string` to `stream`
71 If `stream` is `None`, it defaults to stdout.
73 >>> write_color('Hello world\n')
76 >>> from io import StringIO
77 >>> stream = StringIO()
78 >>> write_color('Hello world\n', 'red', stream)
80 '\x1b[31mHello world\n\x1b[0m'
84 stream.write(color_string(string=string, color=color))