在工作中需要用到使用python输出颜色字符,之前一致间接调用的shell的彩色打印,其实python有更好的彩色打印模块 termcolor, 在http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python中发现这样一句:I'm surprised no one has mentioned the Python termcolor module. Usage is pretty simple:
from termcolor import colored
print colored('hello', 'red'), colored('world', 'green')
于是乎找到链接 http://pypi.python.org/pypi/termcolor 并且体验了一下example如下:
import sys
from termcolor import colored, cprint
text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
print(text)
cprint('Hello, World!', 'green', 'on_red')
print_red_on_cyan = lambda x: cprint(x, 'red', 'on_cyan')
print_red_on_cyan('Hello, World!')
print_red_on_cyan('Hello, Universe!')
for i in range(10):
cprint(i, 'magenta', end=' ')
cprint("Attention!", 'red', attrs=['bold'], file=sys.stderr)
效果如下:
记录下