LinuxGem
我们一起去探寻 Linux 的宝藏吧!
Dvtm -- 平铺式终端

termcolor -- 用 Python 打出彩色终端信息

galeki posted @ 2009年3月27日 02:13 in Bash 和它的朋友们 with tags 终端 termcolor , 1600 阅读
使用 diff2html 将 diff 输出结果转换为高亮 HTML 文本

终端打印的消息可以是彩色的,不过着色的语法确实诡异了一些,也不好阅读。

termcolor 是个 Python 模块,可以帮你输出终端的彩色字,当然语法就好看多啦~

安装 termcolor 之后,只要: 

from termcolor import colored

然后就可以使用 colored 这个方法,对消息进行着色了,比如:

print colored('Hello, World!', 'red')

就会打印出红色的 Hello World!。

除此之外,还可以翻转字体的背景和前景色;用 on_xxx 这样的属性打印出背景和字体颜色不同的消息:

 

 如果经常要用到复杂的颜色组合,可以用 lambda 来把参数抽象出来:

red_on_cyan = lambda x: colored(x, 'red', 'on_cyan')
print red_on_cyan('Hello, World!')

很方便吧~

termcolor 的主页在: http://pypi.python.org/pypi/termcolor/0.1.1

 

 


* 登录
*

simple_captcha.jpg
(输入验证码)