基於win7 + python3.4
import ctypes import sys '''Windows CMD命令行顏色''' # 句柄號 STD_INPUT_HANDLE = -10 STD_OUTPUT_HANDLE= -11 STD_ERROR_HANDLE = -12 # 前景色 FOREGROUND_BLACK = 0x0 # 黑 FOREGROUND_BLUE = 0x01 # 藍 FOREGROUND_GREEN = 0x02 # 綠 FOREGROUND_RED = 0x04 # 紅 FOREGROUND_INTENSITY = 0x08 # 加亮 # 背景色 BACKGROUND_BLUE = 0x10 # 藍 BACKGROUND_GREEN = 0x20 # 綠 BACKGROUND_RED = 0x40 # 紅 BACKGROUND_INTENSITY = 0x80 # 加亮 colors = [FOREGROUND_BLUE, # 藍字 FOREGROUND_GREEN,# 綠字 FOREGROUND_RED, # 紅字 FOREGROUND_BLUE | FOREGROUND_INTENSITY, # 藍字(加亮) FOREGROUND_GREEN | FOREGROUND_INTENSITY, # 綠字(加亮) FOREGROUND_RED | FOREGROUND_INTENSITY, # 紅字(加亮) FOREGROUND_RED | FOREGROUND_INTENSITY| BACKGROUND_BLUE | BACKGROUND_INTENSITY] # 紅字藍底 texts = ['藍字', '綠字', '紅字', '藍字(加亮)', '綠字(加亮)', '紅字(加亮)', '紅字藍底'] # See "http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winprog/winprog/windows_api_reference.asp" for information on Windows APIs. std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) def set_cmd_color(color, handle=std_out_handle): bool = ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color) return bool def reset_color(): set_cmd_color(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE) def print_color_text(color, text): set_cmd_color(color) sys.stdout.write('%s\n' % text) # ==> print(text) reset_color() def print_colors_texts(colors, texts): for color, text in zip(colors, texts): print_color_text(color, text) if __name__ == "__main__": print_colors_texts(colors, texts)