如何向控制台輸出彩色列印資訊呢?如何訂製自己的輸出格式呢?下面將告訴你……
import os
"""
0 All attributes off 預設值
1 Bold (or Bright) 粗體 or 高亮
4 Underline 底線
5 Blink 閃爍
7 Reverse 反顯
30 Black text
31 Red text
32 Green text
33 Yellow text
34 Blue text
35 Purple text
36 Cyan text
37 White text
40 Black background
41 Red background
42 Green background
43 Yellow background
44 Blue background
45 Purple background
46 Cyan background
47 White background
"""
def colored(text, color=None, on_color=None, attrs=None):
fmt_str = '\x1B[;%dm%s\x1B[0m'
if color is not None:
text = fmt_str % (color, text)
if on_color is not None:
text = fmt_str % (on_color, text)
if attrs is not None:
for attr in attrs:
text = fmt_str % (color, text)
return text
def printError(msg):
print colored(msg, color=31)
def printWarning(msg):
print colored(msg, color=33)
def printInfo(msg):
print colored(msg, color=37)
if __name__ == '__main__':
printError("this is an error message!")
printWarning("this is a warning message!")
printInfo("this ia a info message!")
輸出:
參考:
http://www.oschina.net/code/snippet_87675_8599
http://pypi.python.org/pypi/termcolor/0.1.1#downloads