zl程序教程

您现在的位置是:首页 >  Python

当前栏目

Python 命令行cmd指定颜色设置

2023-03-07 09:02:11 时间

目录

· 模块 

· cmd color函数(交互界面)

· Python 颜色大全

· 设置颜色函数  SetConsoleTextArribute

· 打印(输出)

· ▲▲▲总结(代码)


· 模块 

import ctypes

· cmd color函数(交互界面)

C:\Users\zhang>color /?
设置默认的控制台前景和背景颜色。

COLOR [attr]

  attr        指定控制台输出的颜色属性。

颜色属性由两个十六进制数字指定 -- 第一个
对应于背景,第二个对应于前景。每个数字
可以为以下任何值:

    0 = 黑色       8 = 灰色
    1 = 蓝色       9 = 淡蓝色
    2 = 绿色       A = 淡绿色
    3 = 浅绿色     B = 淡浅绿色
    4 = 红色       C = 淡红色
    5 = 紫色       D = 淡紫色
    6 = 黄色       E = 淡黄色
    7 = 白色       F = 亮白色

如果没有给定任何参数,此命令会将颜色还原到 CMD.EXE 启动时
的颜色。这个值来自当前控制台
窗口、/T 命令行开关或 DefaultColor 注册表
值。

如果尝试使用相同的
前景和背景颜色来执行
 COLOR 命令,COLOR 命令会将 ERRORLEVEL 设置为 1

· Python 颜色大全

import ctypes
  
STD_INPUT_HANDLE = -10  
STD_OUTPUT_HANDLE= -11  
STD_ERROR_HANDLE = -12
std_out_handle=ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)

class Text():
    DARKBLUE = 0x01 # 暗蓝色
    DARKGREEN = 0x02 # 暗绿色
    DARKSKYBLUE = 0x03 # 暗天蓝色
    DARKRED = 0x04 # 暗红色
    DARKPINK = 0x05 # 暗粉红色
    DARKYELLOW = 0x06 # 暗黄色
    DARKWHITE = 0x07 # 暗白色
    DARKGRAY = 0x08 # 暗灰色/亮
    BLUE = 0x09 # 蓝色
    GREEN = 0x0a # 绿色
    SKYBLUE = 0x0b # 天蓝色
    RED = 0x0c # 红色
    PINK = 0x0d # 粉红色
    YELLOW = 0x0e # 黄色
    WHITE = 0x0f # 白色

class Background():
    BLUE     = 0x10 # 蓝
    GREEN    = 0x20 # 绿
    RED      = 0x40  # 红
    INTENSITY = 0x80 # 亮

· 设置颜色函数  SetConsoleTextArribute

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

· 打印(输出)

def Print(color:int, string:str(),normal=Text.DARKWHITE):
    SetCmdColor(color)
    print(string)
    SetCmdColor(normal)

· 整合

import ctypes
  
STD_INPUT_HANDLE = -10  
STD_OUTPUT_HANDLE= -11  
STD_ERROR_HANDLE = -12
std_out_handle=ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
class Text():
    DARKBLUE = 0x01 # 暗蓝色
    DARKGREEN = 0x02 # 暗绿色
    DARKSKYBLUE = 0x03 # 暗天蓝色
    DARKRED = 0x04 # 暗红色
    DARKPINK = 0x05 # 暗粉红色
    DARKYELLOW = 0x06 # 暗黄色
    DARKWHITE = 0x07 # 暗白色
    DARKGRAY = 0x08 # 暗灰色/亮
    BLUE = 0x09 # 蓝色
    GREEN = 0x0a # 绿色
    SKYBLUE = 0x0b # 天蓝色
    RED = 0x0c # 红色
    PINK = 0x0d # 粉红色
    YELLOW = 0x0e # 黄色
    WHITE = 0x0f # 白色

class Background():
    BLUE     = 0x10 # 蓝
    GREEN    = 0x20 # 绿
    RED      = 0x40  # 红
    INTENSITY = 0x80 # 亮
 
def SetCmdColor(color, handle=std_out_handle):
    return ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)
 
def Print(color:int, string=str(),normal=Text.DARKWHITE,end='\n'):
    SetCmdColor(color)
    print(string,end=end)
    #SetCmdColor(normal)

if __name__ == '__main__':
    for t, c in zip(list('python颜色'),(Text.BLUE, Text.GREEN, Text.RED, Text.PINK, Text.YELLOW, Text.WHITE, Text.DARKSKYBLUE, Text.YELLOW|Text.WHITE|Background.GREEN)):
        Print(c, t, end=str())
    input()

提示: 一行中只能存在一种颜色