python终端颜色设置

时间:2021-08-07 09:09:52

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.自定义颜色函数

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

3.1使用方法

from color import Colors

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

参考:

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

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

https://taizilongxu.gitbooks.io/*-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')