前言
最近在項(xiàng)目中需要輸出彩色的文字來提醒用戶,以前寫過,但是只能在win上面運(yùn)行。
今天搜了下看有沒有在win和Linux上通用的輸出彩色文字的模塊,結(jié)果發(fā)現(xiàn)沒有,,于是就自己弄了一個(gè),分享下,以后用的時(shí)候翻翻博客,方便別人也方便自己。
win下輸出彩色文字,網(wǎng)上有兩種方法一種是用system執(zhí)行命令來設(shè)置顏色,感覺還是不太好,用ctypes模塊實(shí)現(xiàn)更好點(diǎn)。
linux下設(shè)置顏色,網(wǎng)上只找到了一種方法,下面不廢話了,直接貼下代碼:
示例代碼
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 + ' ') resetCmdColor() def printGreen(msg): setCmdColor(foreGroundGREEN) sys.stdout.write(msg + ' ') resetCmdColor() def printRed(msg): setCmdColor(foreGroundRED) sys.stdout.write(msg + ' ') resetCmdColor() def printYellow(msg): setCmdColor(foreGroundYELLOW) sys.stdout.write(msg + ' ') 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 = '