Python print 打印 颜色设置

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
def set_str_style(string, mode='', fore='', back=''):
_style_table = {
'fore':
{ # 前景色
'black': 30, # 黑色
'red': 31, # 红色
'green': 32, # 绿色
'yellow': 33, # 黄色
'blue': 34, # 蓝色
'purple': 35, # 紫红色
'cyan': 36, # 青蓝色
'white': 37, # 白色
},

'back':
{ # 背景
'black': 40, # 黑色
'red': 41, # 红色
'green': 42, # 绿色
'yellow': 43, # 黄色
'blue': 44, # 蓝色
'purple': 45, # 紫红色
'cyan': 46, # 青蓝色
'white': 47, # 白色
},

'mode':
{ # 显示模式
'mormal': 0, # 终端默认设置
'bold': 1, # 高亮显示
'underline': 4, # 使用下划线
'blink': 5, # 闪烁
'invert': 7, # 反白显示
'hide': 8, # 不可见
}
}

mode = str(_style_table.get('mode', {}).get(mode, ''))
fore = str(_style_table.get('fore', {}).get(fore, ''))
back = str(_style_table.get('back', {}).get(back, ''))

return f"\033[{';'.join([s for s in [mode, fore, back] if s])}m{string}\033[0m"

测试代码

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
print(set_str_style('高亮', mode='bold'))
print(set_str_style('下划线', mode='underline'))
print(set_str_style('闪烁', mode='blink'))
print(set_str_style('反白', mode='invert'))
print(set_str_style('不可见', mode='hide'))
print('')
print(set_str_style('黑色', fore='black'))
print(set_str_style('红色', fore='red'))
print(set_str_style('绿色', fore='green'))
print(set_str_style('黄色', fore='yellow'))
print(set_str_style('蓝色', fore='blue'))
print(set_str_style('紫红色', fore='purple'))
print(set_str_style('青蓝色', fore='cyan'))
print(set_str_style('白色', fore='white'))
print('')
print(set_str_style('黑色', back='black'))
print(set_str_style('红色', back='red'))
print(set_str_style('绿色', back='green'))
print(set_str_style('黄色', back='yellow'))
print(set_str_style('蓝色', back='blue'))
print(set_str_style('紫红色', back='purple'))
print(set_str_style('青蓝色', back='cyan'))
print(set_str_style('白色', back='white'))
print('')
print(set_str_style('正常显示'))
print(set_str_style('混合显示', mode='underline', fore='red', back='yellow'))

Python print 打印 颜色设置
https://itxiaopang.github.io/p/39d03d23612e4dbebd1115c4919d0a29/
作者
挨踢小胖
发布于
2021年9月11日
许可协议