Created
March 21, 2017 06:46
-
-
Save sing1ee/aca120409e01584d055d2c42a801df39 to your computer and use it in GitHub Desktop.
small tools for colorful output of stdout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# /usr/bin/python | |
# -*- coding: utf-8 -*- | |
import sys | |
reload(sys) | |
sys.setdefaultencoding('utf8') # @UndefinedVariable | |
# 格式:\033[显示方式;前景色;背景色m | |
# 说明: | |
# | |
# 前景色 背景色 颜色 | |
# --------------------------------------- | |
# 30 40 黑色 | |
# 31 41 红色 | |
# 32 42 绿色 | |
# 33 43 黃色 | |
# 34 44 蓝色 | |
# 35 45 紫红色 | |
# 36 46 青蓝色 | |
# 37 47 白色 | |
# | |
# 显示方式 意义 | |
# ------------------------- | |
# 0 终端默认设置 | |
# 1 高亮显示 | |
# 4 使用下划线 | |
# 5 闪烁 | |
# 7 反白显示 | |
# 8 不可见 | |
# | |
# 例子: | |
# \033[1;31;40m <!--1-高亮显示 31-前景色红色 40-背景色黑色--> | |
# \033[0m <!--采用终端默认设置,即取消颜色设置-->]]] | |
STYLE = { | |
'fore': | |
{ # 前景色 | |
'black': 30, # 黑色 | |
'red': 31, # 红色 | |
'green': 32, # 绿色 | |
'yellow': 33, # 黄色 | |
'blue': 34, # 蓝色 | |
'purple': 35, # 紫红色 | |
'cyan': 36, # 青蓝色 | |
'white': 37, # 白色 | |
}, | |
'back': | |
{ # 背景 | |
'black': 40, # 黑色 | |
'red': 41, # 红色 | |
'green': 42, # 绿色 | |
'yellow': 43, # 黄色 | |
'blue': 44, # 蓝色 | |
'purple': 45, # 紫红色 | |
'cyan': 46, # 青蓝色 | |
'white': 47, # 白色 | |
}, | |
'mode': | |
{ # 显示模式 | |
'mormal': 0, # 终端默认设置 | |
'bold': 1, # 高亮显示 | |
'underline': 4, # 使用下划线 | |
'blink': 5, # 闪烁 | |
'invert': 7, # 反白显示 | |
'hide': 8, # 不可见 | |
}, | |
'default': | |
{ | |
'end': 0, | |
}, | |
} | |
def color_str(string, mode='', fore='', back=''): | |
mode = '%s' % STYLE['mode'][mode] if STYLE['mode'].has_key(mode) else '' | |
fore = '%s' % STYLE['fore'][fore] if STYLE['fore'].has_key(fore) else '' | |
back = '%s' % STYLE['back'][back] if STYLE['back'].has_key(back) else '' | |
style = ';'.join([s for s in [mode, fore, back] if s]) | |
style = '\033[%sm' % style if style else '' | |
end = '\033[%sm' % STYLE['default']['end'] if style else '' | |
return '%s%s%s' % (style, string, end) | |
if __name__ == '__main__': | |
args = sys.argv[1:] | |
print args | |
pattern_color = {} | |
if args: | |
pattern_color = dict((x[0], x[1]) for x in (map(lambda x: x.split("|"), args))) | |
while True: | |
line = sys.stdin.readline() | |
if not line: | |
break | |
color = None | |
for pattern, c in pattern_color.items(): | |
if pattern in line: | |
color = c | |
if color: | |
print color_str(line, fore=color) | |
else: | |
print line | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment