1 # -*- coding: utf-8 -*- |
1 # -*- coding: utf-8 -*- |
2 |
2 |
|
3 # support Python 2.6+ |
|
4 from __future__ import print_function |
|
5 |
|
6 |
|
7 #: Set disabled = True to disable all colors. |
|
8 disabled = False |
|
9 |
|
10 |
|
11 #: Supported colors as enum and string names. |
3 (BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, BOLD) = range(0,9) |
12 (BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, BOLD) = range(0,9) |
|
13 names = ['black','red','green','yellow','blue','magenta','cyan','white','bold'] |
4 |
14 |
5 names = ['black','red','green','yellow','blue','magenta','cyan','white'] |
|
6 |
|
7 disabled = False # set True to disable all colors |
|
8 |
15 |
9 def highlight(enable, fg=None, bg=None): |
16 def highlight(enable, fg=None, bg=None): |
10 ''' |
17 """Return ANSI escape code for selected color and font style. |
11 |
18 |
12 highlight(1) -- switch to bold, keep previous color |
19 Set `enable` to true value to enable highlighting, false to disable/end highlighting. |
13 highlight(1, RED) -- red foreground |
|
14 highlight(1, BOLD + YELLOW, BLUE) -- yellow on blue, bold |
|
15 highlight(0) -- reset |
|
16 |
20 |
17 ''' |
21 Set color and style using `fg` and `bg`. These parameters will accept |
|
22 string or variables defined in this module (BLACK, ...). |
|
23 |
|
24 Usage example:: |
|
25 |
|
26 highlight(1) -- switch to bold, keep previous color |
|
27 highlight(1, 'bold red') -- bold red foreground |
|
28 highlight(1, BOLD | YELLOW, BLUE) -- yellow on blue, bold |
|
29 highlight(0) -- reset |
|
30 |
|
31 """ |
18 global disabled |
32 global disabled |
19 if disabled: |
33 if disabled: |
20 return '' |
34 return '' |
21 |
35 |
22 if isinstance(fg, str): |
36 if isinstance(fg, str): |
23 fg = names.index(fg) |
37 fg = sum(names.index(item.lower()) for item in fg.split()) |
24 if isinstance(bg, str): |
38 if isinstance(bg, str): |
25 bg = names.index(bg) |
39 bg = sum(names.index(item.lower()) for item in bg.split()) |
26 |
40 |
27 if enable: |
41 if enable: |
28 code = '1' |
42 code = '1' |
29 if fg is not None: |
43 if fg is not None: |
30 code = '' |
44 code = '' |
40 code += str(40 + bg) |
54 code += str(40 + bg) |
41 return "\033[" + code + "m" |
55 return "\033[" + code + "m" |
42 else: |
56 else: |
43 return "\033[0m" |
57 return "\033[0m" |
44 |
58 |
45 def set_highlight(enable, fg=None, bg=None): |
|
46 print(highlight(enable, fg, bg), end='') |
|
47 |
59 |
|
60 def hprint(*args, **kwargs): |
|
61 """Highlighted print. |
|
62 |
|
63 Usage is same as for print function. |
|
64 Whole output is colored as specified by `fg`, `bg` parameters. |
|
65 |
|
66 Usage example:: |
|
67 |
|
68 hprint('Hello in red!', fg='bold red') |
|
69 |
|
70 """ |
|
71 fg = kwargs.pop('fg', None) |
|
72 bg = kwargs.pop('bg', None) |
|
73 end = kwargs.pop('end', '\n') |
|
74 print(highlight(1, fg, bg), end='') |
|
75 print(*args, end='', **kwargs) |
|
76 print(highlight(0), end=end) |
|
77 |