现在的位置: 首页 > 综合 > 正文

python 自定义linux控制台输出

2013年05月04日 ⁄ 综合 ⁄ 共 951字 ⁄ 字号 评论关闭

如何向控制台输出彩色打印信息呢?如何订制自己的输出格式呢?下面将告诉你……

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

 

【上篇】
【下篇】

抱歉!评论已关闭.