zhanmeiliang

1.颜色定义说明

格式:\033[显示方式;前景色;背景色m
 
前景色  背景色  颜色
---------------------------------------
30     40    黑色
31     41    红色
32     42    绿色
33     43    黃色
34     44    蓝色
35     45    紫红色
36     46    青蓝色
37     47    白色
 
显示方式  意义
-------------------------
0     终端默认设置
1     高亮显示
4     使用下划线
5     闪烁
7     反白显示
8     不可见 
例子:
\033[1;31;40m <!--1-高亮显示 31-前景色红色 40-背景色黑色-->
\033[0m <!--采用终端默认设置,即取消颜色设置-->]]]        
 

2.ANSI控制码的说明 

\33[0m         关闭所有属性 
\33[1m         设置高亮度 
\33[4m         下划线 
\33[5m         闪烁 
\33[7m         反显 
\33[8m         消隐 
\33[30m -- \33[37m   设置前景色 
\33[40m -- \33[47m   设置背景色 
\33[nA          光标上移n行 
\33[nB          光标下移n行 
\33[nC          光标右移n行 
\33[nD          光标左移n行 
\33[y;xH         设置光标位置 
\33[2J           清屏 
\33[K            清除从光标到行尾的内容 
\33[s            保存光标位置 
\33[u            恢复光标位置 
\33[?25l          隐藏光标 
\33[?25h         显示光标
 

3.自定义颜色函数

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # author:zml
 4 
 5 def Colors(text, fcolor=None,bcolor=None,style=None):
 6     \'\'\'
 7     自定义字体样式及颜色
 8     \'\'\'
 9     # 字体颜色
10     fg={
11        \'black\': \'\033[30m\',     #字体黑
12        \'red\': \'\033[31m\',       #字体红
13        \'green\': \'\033[32m\',     #字体绿
14        \'yellow\': \'\033[33m\',    #字体黄
15        \'blue\': \'\033[34m\',      #字体蓝
16        \'magenta\': \'\033[35m\',   #字体紫
17        \'cyan\': \'\033[36m\',      #字体青
18        \'white\':\'\033[37m\',      #字体白
19         \'end\':\'\033[0m\'         #默认色
20     }
21     # 背景颜色
22     bg={
23        \'black\': \'\033[40m\',     #背景黑
24        \'red\': \'\033[41m\',       #背景红
25        \'green\': \'\033[42m\',     #背景绿
26        \'yellow\': \'\033[43m\',    #背景黄
27        \'blue\': \'\033[44m\',      #背景蓝
28        \'magenta\': \'\033[45m\',   #背景紫
29        \'cyan\': \'\033[46m\',      #背景青
30        \'white\':\'\033[47m\',      #背景白
31     }
32     # 内容样式
33     st={
34         \'bold\': \'\033[1m\',      #高亮
35         \'url\': \'\033[4m\',       #下划线
36         \'blink\': \'\033[5m\',     #闪烁
37         \'seleted\': \'\033[7m\',   #反显
38     }
39 
40     if fcolor in fg:
41         text=fg[fcolor]+text+fg[\'end\']
42     if bcolor in bg:
43         text = bg[bcolor] + text + fg[\'end\']
44     if style in st:
45         text = st[style] + text + fg[\'end\']
46     return text

3.1使用方法

from color import Colors

print(Colors(\'文本内容\',\'字体颜色\',\'背景颜色\',\'字体样式\'))

参考:

http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python

http://blog.csdn.net/gatieme/article/details/45439671

https://taizilongxu.gitbooks.io/stackoverflow-about-python/content/30/README.html

http://www.361way.com/python-color/4596.html

总结:

可以使用python的termcolor模块,简单快捷。避免重复造轮子

from termcolor import colored
print colored(\'hello\', \'red\'), colored(\'world\', \'green\')

分类:

技术点:

相关文章: