Python让你的终端输出变得五彩斑斓

前言

也许你希望在终端上输出一些带有颜色或者粗体、下划线等样式的信息,就像man中的那样;
又或者海量的信息堆砌在控制台导致各种信息都显示在一起,让人抓不住重点,或者使用python处理文档文件的时候,希望能看到一些中重点语句。
这时候,如果能给重要的信息加上差异的字体颜色,那么就会更加显眼,增加使用者可阅读性。
本文来简单介绍一下如何实现在终端变换颜色。

Linux下终端变换颜色

linux和windows平台修改终端显示颜色的方式是不一样的,当然其实也有通用的方法,这个在本文最后会讲。
先说一下Linux平台的方法,使用转义序列来实现不同颜色的显示。
转义序列是以ESC开头,即用\033来完成(ESC的ASCII码用十进制表示是27,用八进制表示就是033)。而终端的字符颜色是用转义序列控制的,是文本模式下的系统显示功能,和具体的语言无关。
它的格式如下:

\033[显示方式;前景色;背景色m

其中显示方式,前景色,背景色参数如下:

前景色背景色颜色显示方式意义
3040黑色0终端默认设置
3141红色1粗体 高亮显示
3242绿色22非粗体 非高亮显示
3343黃色4使用下划线
3444蓝色24去下划线
3545紫红色5闪烁
3646青蓝色25去闪烁
3747白色7反白显示
27非反显
8不可见
28可见

前景色后景色可以不设置,显示方式也可以不设置(默认为0)

print('\033[0;31;1m' )
print('*' * 50) 
print('*HOST:\t', 2019) 
print('*URI:\t', 'http://127.0.0.1') 
print('*TIME:\t', '20:58') 
print('*' * 50) 
print('\033[0m')

输出结果如下:
shell显示
测试文件如下:

#   格式:\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 UseStyle(string, mode = '', fore = '', back = ''):
    mode  = '%s' % STYLE['mode'][mode] if mode in STYLE['mode'] else ''
    fore  = '%s' % STYLE['fore'][fore] if fore in STYLE['fore'] else ''
    back  = '%s' % STYLE['back'][back] if back in STYLE['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)

def TestColor( ):
    print (UseStyle('正常显示'))

    print ("测试显示模式")
    print (UseStyle('高亮',   mode = 'bold'))
    print (UseStyle('下划线', mode = 'underline'))
    print (UseStyle('闪烁',   mode = 'blink'))
    print (UseStyle('反白',   mode = 'invert'))
    print (UseStyle('不可见', mode = 'hide'))

    print ("测试前景色")
    print (UseStyle('黑色',   fore = 'black'))
    print (UseStyle('红色',   fore = 'red'))
    print (UseStyle('绿色',   fore = 'green'))
    print (UseStyle('黄色',   fore = 'yellow'))
    print (UseStyle('蓝色',   fore = 'blue'))
    print (UseStyle('紫红色', fore = 'purple'))
    print (UseStyle('青蓝色', fore = 'cyan'))
    print (UseStyle('白色',   fore = 'white'))

    print ("测试背景色")
    print (UseStyle('黑色',   back = 'black'))
    print (UseStyle('红色',   back = 'red'))
    print (UseStyle('绿色',   back = 'green'))
    print (UseStyle('黄色',   back = 'yellow'))
    print (UseStyle('蓝色',   back = 'blue'))
    print (UseStyle('紫红色', back = 'purple'))
    print (UseStyle('青蓝色', back = 'cyan'))
    print (UseStyle('白色',   back = 'white'))

if __name__ == '__main__':
    TestColor( )

结果如下:
在这里插入图片描述
各种模式与颜色对比图如下:
qiqiyingse

window下终端颜色显示

windows下面稍微有点不一样

import ctypes,sys

STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12

# 字体颜色定义 ,关键在于颜色编码,由2位十六进制组成,分别取0~f,前一位指的是背景色,后一位指的是字体色
#由于该函数的限制,应该是只有这16种,可以前景色与背景色组合。也可以几种颜色通过或运算组合,组合后还是在这16种颜色中

# Windows CMD命令行 字体颜色定义 text colors
FOREGROUND_BLACK = 0x00 # black.
FOREGROUND_DARKBLUE = 0x01 # dark blue.
FOREGROUND_DARKGREEN = 0x02 # dark green.
FOREGROUND_DARKSKYBLUE = 0x03 # dark skyblue.
FOREGROUND_DARKRED = 0x04 # dark red.
FOREGROUND_DARKPINK = 0x05 # dark pink.
FOREGROUND_DARKYELLOW = 0x06 # dark yellow.
FOREGROUND_DARKWHITE = 0x07 # dark white.
FOREGROUND_DARKGRAY = 0x08 # dark gray.
FOREGROUND_BLUE = 0x09 # blue.
FOREGROUND_GREEN = 0x0a # green.
FOREGROUND_SKYBLUE = 0x0b # skyblue.
FOREGROUND_RED = 0x0c # red.
FOREGROUND_PINK = 0x0d # pink.
FOREGROUND_YELLOW = 0x0e # yellow.
FOREGROUND_WHITE = 0x0f # white.

# Windows CMD命令行 背景颜色定义 background colors
BACKGROUND_BLUE = 0x10 # dark blue.
BACKGROUND_GREEN = 0x20 # dark green.
BACKGROUND_DARKSKYBLUE = 0x30 # dark skyblue.
BACKGROUND_DARKRED = 0x40 # dark red.
BACKGROUND_DARKPINK = 0x50 # dark pink.
BACKGROUND_DARKYELLOW = 0x60 # dark yellow.
BACKGROUND_DARKWHITE = 0x70 # dark white.
BACKGROUND_DARKGRAY = 0x80 # dark gray.
BACKGROUND_BLUE = 0x90 # blue.
BACKGROUND_GREEN = 0xa0 # green.
BACKGROUND_SKYBLUE = 0xb0 # skyblue.
BACKGROUND_RED = 0xc0 # red.
BACKGROUND_PINK = 0xd0 # pink.
BACKGROUND_YELLOW = 0xe0 # yellow.
BACKGROUND_WHITE = 0xf0 # white.

# get handle
std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)

def set_cmd_text_color(color, handle=std_out_handle):
    Bool = ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)
    return Bool

#reset white
def resetColor():
    set_cmd_text_color(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)

###############################################################

#暗蓝色
#dark blue
def printDarkBlue(mess):
    set_cmd_text_color(FOREGROUND_DARKBLUE)
    sys.stdout.write(mess)
    resetColor()

#暗绿色
#dark green
def printDarkGreen(mess):
    set_cmd_text_color(FOREGROUND_DARKGREEN)
    sys.stdout.write(mess)
    resetColor()

#暗天蓝色
#dark sky blue
def printDarkSkyBlue(mess):
    set_cmd_text_color(FOREGROUND_DARKSKYBLUE)
    sys.stdout.write(mess)
    resetColor()

#暗红色
#dark red
def printDarkRed(mess):
    set_cmd_text_color(FOREGROUND_DARKRED)
    sys.stdout.write(mess)
    resetColor()

#暗粉红色
#dark pink
def printDarkPink(mess):
    set_cmd_text_color(FOREGROUND_DARKPINK)
    sys.stdout.write(mess)
    resetColor()

#暗黄色
#dark yellow
def printDarkYellow(mess):
    set_cmd_text_color(FOREGROUND_DARKYELLOW)
    sys.stdout.write(mess)
    resetColor()

#暗白色
#dark white
def printDarkWhite(mess):
    set_cmd_text_color(FOREGROUND_DARKWHITE)
    sys.stdout.write(mess)
    resetColor()

#暗灰色
#dark gray
def printDarkGray(mess):
    set_cmd_text_color(FOREGROUND_DARKGRAY)
    sys.stdout.write(mess)
    resetColor()

#蓝色
#blue
def printBlue(mess):
    set_cmd_text_color(FOREGROUND_BLUE)
    sys.stdout.write(mess)
    resetColor()

#绿色
#green
def printGreen(mess):
    set_cmd_text_color(FOREGROUND_GREEN)
    sys.stdout.write(mess)
    resetColor()

#天蓝色
#sky blue
def printSkyBlue(mess):
    set_cmd_text_color(FOREGROUND_SKYBLUE)
    sys.stdout.write(mess)
    resetColor()

#红色
#red
def printRed(mess):
    set_cmd_text_color(FOREGROUND_RED)
    sys.stdout.write(mess)
    resetColor()

#粉红色
#pink
def printPink(mess):
    set_cmd_text_color(FOREGROUND_PINK)
    sys.stdout.write(mess)
    resetColor()

#黄色
#yellow
def printYellow(mess):
    set_cmd_text_color(FOREGROUND_YELLOW)
    sys.stdout.write(mess)
    resetColor()

#白色
#white
def printWhite(mess):
    set_cmd_text_color(FOREGROUND_WHITE)
    sys.stdout.write(mess)
    resetColor()
##################################################

#白底黑字
#white bkground and black text
def printWhiteBlack(mess):
    set_cmd_text_color(FOREGROUND_BLACK | BACKGROUND_WHITE)
    sys.stdout.write(mess)
    resetColor()
#白底黑字
#white bkground and black text
def printWhiteBlack_2(mess):
    set_cmd_text_color(0xf0)
    sys.stdout.write(mess)
    resetColor()

#黄底蓝字
#white bkground and black text
def printYellowRed(mess):
    set_cmd_text_color(BACKGROUND_YELLOW | FOREGROUND_RED)
    sys.stdout.write(mess)
    resetColor()

##############################################################
if __name__ == '__main__': 
    print
    printDarkBlue(u'printDarkBlue:暗蓝色文字\n')
    printDarkGreen(u'printDarkGreen:暗绿色文字\n')
    printDarkSkyBlue(u'printDarkSkyBlue:暗天蓝色文字\n')
    printDarkRed(u'printDarkRed:暗红色文字\n')
    printDarkPink(u'printDarkPink:暗粉红色文字\n')
    printDarkYellow(u'printDarkYellow:暗黄色文字\n')
    printDarkWhite(u'printDarkWhite:暗白色文字\n')
    printDarkGray(u'printDarkGray:暗灰色文字\n')
    printBlue(u'printBlue:蓝色文字\n')
    printGreen(u'printGreen:绿色文字\n')
    printSkyBlue(u'printSkyBlue:天蓝色文字\n')
    printRed(u'printRed:红色文字\n')
    printPink(u'printPink:粉红色文字\n')
    printYellow(u'printYellow:黄色文字\n')
    printWhite(u'printWhite:白色文字\n')
    printWhiteBlack(u'printWhiteBlack:白底黑字输出\n')
    printWhiteBlack_2(u'printWhiteBlack_2:白底黑字输出\n')
    printYellowRed(u'printYellowRed:黄底红字输出\n')

平台通用的方法

python 有一个库colorama , 这个库可以支持修改颜色

pip3 install colorama

实例

from colorama import init, Fore, Back, Style

if __name__ == "__main__":
    init(autoreset=True)    #  初始化,并且设置颜色设置自动恢复
    # 如果未设置autoreset=True,需要使用如下代码重置终端颜色为初始设置
    #print(Fore.RESET + Back.RESET + Style.RESET_ALL)  autoreset=True
    print(Fore.RED + 'some red text')
    print(Back.GREEN + 'and with a green background')
    print(Style.DIM + 'and in dim text')
    print('back to normal now')

最后的最后

找到一个两个平台通用的代码,其实就是上面介绍的方法整合一下:

import platform
if 'Windows' in platform.system():
	import sys
	import ctypes
	__stdInputHandle = -10
	__stdOutputHandle = -11
	__stdErrorHandle = -12
	__foreGroundBLUE = 0x09
 	__foreGroundGREEN = 0x0a
	__foreGroundRED = 0x0c
	__foreGroundYELLOW = 0x0e
	stdOutHandle=ctypes.windll.kernel32.GetStdHandle(__stdOutputHandle)
	def setCmdColor(color,handle=stdOutHandle):
		return ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)
	def resetCmdColor():
		setCmdColor(__foreGroundRED | __foreGroundGREEN | __foreGroundBLUE)
	def printBlue(msg):
		setCmdColor(__foreGroundBLUE)
		sys.stdout.write(msg + '\n')
		resetCmdColor()
	def printGreen(msg):
		setCmdColor(__foreGroundGREEN)
		sys.stdout.write(msg + '\n')
		resetCmdColor()
	def printRed(msg):
		setCmdColor(__foreGroundRED)
		sys.stdout.write(msg + '\n')
		resetCmdColor()
	def printYellow(msg):
		setCmdColor(__foreGroundYELLOW)
		sys.stdout.write(msg + '\n')
		resetCmdColor()
else:
	STYLE = {
	'fore':{
	'red': 31,
	'green': 32,
	'yellow': 33,
	'blue': 34,
	}
	}
	def UseStyle(msg, mode = '', fore = '', back = '40'):
		fore = '%s' % STYLE['fore'][fore] if STYLE['fore'].has_key(fore) else ''
		style = ';'.join([s for s in [mode, fore, back] if s])
		style = '\033[%sm' % style if style else ''
		end = '\033[%sm' % 0 if style else ''
		return '%s%s%s' % (style, msg, end)
	def printRed(msg):
		print UseStyle(msg,fore='red')
	def printGreen(msg):
		print UseStyle(msg,fore='green')
	def printYellow(msg):
		print UseStyle(msg,fore='yellow')
	def printBlue(msg):
		print UseStyle(msg,fore='blue')
posted @ 2019-05-17 15:00  枫奇丶宛南  阅读(200)  评论(0编辑  收藏  举报