Python设置终端显示颜色、粗体、下划线等效果
也许你希望在终端上输出一些带有颜色或者粗体、下划线等样式的信息,就像man中的那样,那么这篇文章将会起到些许作用。
在Linux终端中,使用转义序列来进行如上所述的显示,转义序列以ESC开头,即ASCII码下的\033,其格式为:
\033[显示方式;前景色;背景色m
显示方式、前景色、背景色至少一个存在即可。
其中:
显示方式:0(关闭所有效果),1(高亮),4(下划线),5(闪烁),7(反色),8(不可见)。
前景色以3开头,背景色以4开头,具体颜色值有:0(黑色),1(红色),2(绿色),3(黄色),4(蓝色),5(紫色),6(青色),7(白色)。即前景绿色为32,背景蓝色为44。
下面是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 | #! /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, 'blink': 5, 'invert': 7,         },         'default': {                 'end': 0,         } } def use_style(string, mode='', fore='', back=''):     mode = '%s' % STYLE['mode'][mode] if STYLE['mode'].has_key(mode) else ''     fore = '%s' % STYLE['fore'][fore] if STYLE['fore'].has_key(fore) else ''     back = '%s' % STYLE['back'][back] if STYLE['back'].has_key(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 test():     print use_style('Normal')     print use_style('Bold', mode='bold')     print use_style('Underline & red text', mode='underline', fore='red')     print use_style('Invert & green back', mode='reverse', back='green')     print use_style('Black text & White back', fore='black', back='white') if __name__ == '__main__':     test() | 
本文内容遵从CC3.0版权协议,转载请注明:转自Pythoner
本文链接地址:Python设置终端显示颜色、粗体、下划线等效果


这么花哨![[em_xiao]](http://www.pythoner.com/wp-includes/images/smilies/xiao.gif)
windows下起作用吗?![[em_mobai]](http://www.pythoner.com/wp-includes/images/smilies/mobai.gif)
不起作用,windows可以看下这个:http://www.oschina.net/code/snippet_2008177_38590
我这里怎么显示
# zt @ ztlinux in ~/Desktop/lianxi [9:19:43] C:1
$ python3 style.py
File “style.py”, line 31
print use_style(‘Normal’)
^
SyntaxError: invalid syntax
python3应使用print()方法