-
Notifications
You must be signed in to change notification settings - Fork 0
/
colors.py
52 lines (39 loc) · 1.21 KB
/
colors.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import sys
import re
def _has_colors(stream):
if not hasattr(stream, 'isatty'):
return False
if not stream.isatty():
return False
try:
import curses
curses.setupterm()
return curses.tigetnum('colors') > 2
except:
return False
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = list(range(8))
NORMAL, BOLD, DARK, ITALICS, UNDERLINE,\
_, _, INVERT, CLEAR, STRIKETHROUGH = list(range(10))
LIGHT = 'light'
_has_colors = _has_colors(sys.stdout)
ansi_escape = re.compile(r'\x1b[^m]*m')
def colorStr(text, fg=None, bg=None, style=None):
if _has_colors:
if style == LIGHT:
fg += 60
style = None
seq = '\x1b['
seq += str(0 if bg is None else (bg + 40)) + ';'
seq += (str(style) + ';') if style is not None else ''
seq += str((WHITE if fg is None else fg) + 30)
seq += 'm{}\x1b[0m'.format(text)
return seq
else:
return text
def bold(t, yes=True):
return colorStr(t, style=BOLD) if yes else t
def unColorStr(text):
return ansi_escape.sub('', text)
if __name__ == '__main__':
for style in range(10):
print(colorStr('hello world', fg=RED, style=style))