Thursday, November 20, 2008

[Python]使用ansi color code 让console五颜六色

写了一个Python小程序, 用于输出带ansi color code的字符串,使得在支持vt100的终端上能看见五颜六色的输出。

ESC = chr(27)
# 字体
a_default = 0
a_bold = 1
a_italic = 3
a_underline= 4
# 前景颜色
fg_black = 30
fg_red = 31
fg_green = 32
fg_yellow = 33
fg_blue = 34
fg_magenta = 35
fg_cyan = 36
fg_white = 37
# 后景颜色
bg_black = 40
bg_red = 41
bg_green = 42
bg_yellow = 43
bg_blue = 44
bg_magenta = 45
bg_cyan = 46
bg_white = 47

def color_code(a):
return ESC+"[%dm"%a

def color_str(s, *args):
cs = ""
for a in args:
cs += color_code(a)
cs += s
cs += color_code(a_default)
return cs

用法
比如你可以用

print color_str("hello world", fg_red, bg_black, a_bold)

来生成黑底红字的加粗的hello world

No comments: