python終端顏色設置

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 Colorshtml

print(Colors('文本內容','字體顏色','背景顏色','字體樣式'))python

參考:

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

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.htmlurl

總結:

可使用python的termcolor模塊,簡單快捷。避免重複造輪子spa

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

相關文章
相關標籤/搜索