Life is Short

使用python在终端输出带有样式的文本

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
Author : myth
Date : 15-5-14
Email : belongmyth at 163.com
'''
Styles = dict(
list(zip(list(range(1, 9)),[
'bold',
'dark',
'',
'underline',
'blink',
'',
'reverse',
'concealed'
]
))
)
for k,v in Styles.items():
if v == '':
del Styles[k]
ForegroundColors = dict(
list(zip(list(range(30, 38)),[
'grey',
'red',
'green',
'yellow',
'blue',
'magenta',
'cyan',
'white',
]
))
)
BackgroundColors = dict(
list(zip(list(range(40, 48)),[
'on_grey',
'on_red',
'on_green',
'on_yellow',
'on_blue',
'on_magenta',
'on_cyan',
'on_white'
]
))
)
max_length = max([len(v) for v in Styles.values()]) + max([len(v) for v in ForegroundColors.values()]) + max([len(v) for v in BackgroundColors.values()])
def print_format_table():
"""
prints table of formatted text format options
"""
for style, styleMsg in Styles.items():
for fg, fgMsg in ForegroundColors.items():
s1 = ''
for bg, bgMsg in BackgroundColors.items():
format = ';'.join([str(style), str(fg), str(bg)])
formatMsg = '-'.join([styleMsg, fgMsg, bgMsg]).center(max_length+3)
s1 += '\x1b[%sm %s \x1b[0m' % (format, formatMsg)
print s1
print ''
print_format_table()