码迷,mamicode.com
首页 > 编程语言 > 详细

python 控制 cmd 命令行颜色

时间:2016-03-05 14:36:54      阅读:574      评论:0      收藏:0      [点我收藏+]

标签:

基于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) 

 

python 控制 cmd 命令行颜色

标签:

原文地址:http://www.cnblogs.com/hhh5460/p/5244750.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!