8

Python终端显示设置颜色、粗体、下划线等样式

 3 years ago
source link: https://xushanxiang.com/2019/08/python-settings-terminal-display-style.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python终端显示设置颜色、粗体、下划线等样式

作者: xusx 分类: Python 发布时间: 2019-08-20 10:31

我们在Linux或Mac OS X终端中,可以使用转义序列使显示的样式做些改变,使终端内容更具可读性。

转义序列以ESC开头,即ASCII码下的\033,其格式为:
\033[显示方式;前景色;背景色m
显示方式、前景色、背景色至少一个存在即可。

显示方式:0-关闭所有效果,1-加粗,4-下划线,5-闪烁,7-反色,8-不可见。

前背景色:以3开头,背景色以4开头,颜色值有:0-黑色,1-红色,2-绿色,3-黄色,4-蓝色,5-紫色,6-青色,7-白色。

如,前景绿色为32 – print ‘\033[32m’,背景蓝色为44 – print ‘\033[44m’

注意:要结束特殊样式,请再使用 print ‘\033[0m’

代码示例:

#! /usr/bin/python
# coding=utf-8

STYLE = {
'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': {
'bold': 1, 'underline': 4, 'invert': 7,
},
'default': {
'end': 0,
}
}


def use_style(string, mode='', fore='', back=''):
mode = '%s' % STYLE['mode'][mode] if mode in STYLE['mode'] else ''
fore = '%s' % STYLE['fore'][fore] if fore in STYLE['fore'] else ''
back = '%s' % STYLE['back'][back] if back in STYLE['back'] else ''
style = ';'.join([s for s in [mode, fore, back] if s])
style = '\033[%sm' % style if style else ''
end = '\033[%sm' % STYLE['default']['end'] if style else ''
return '%s%s%s' % (style, string, end)


def start():
print use_style('正常')
print use_style('粗体', mode='bold')
print use_style('下划线和红色文字', mode='underline', fore='red')
print use_style('反转和蓝色背景', mode='reverse', back='blue')
print use_style('黑色文字和白色背景', fore='white', back='black')


if __name__ == '__main__':
start()

粗体

下划线和红色文字

反转和蓝色背景

白色文字和黑色背景

如果转义一下 \033[%sm 变为 \\033[%sm,我们可以看到运行结果(源码):

正常
\033[1m粗体\033[0m
\033[4;31m下划线和红色文字\033[0m
\033[44m反转和蓝色背景\033[0m
\033[37;40m黑色文字和白色背景\033[0m

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!

发表评论 取消回复

电子邮件地址不会被公开。 必填项已用*标注


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK