python控制檯輸出彩色字體

python控制檯輸出彩色字體

在這裏插入圖片描述


import ctypes, sys

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

# 字體顏色定義 text colors
FOREGROUND_BLUE = 0x09  # blue.
FOREGROUND_GREEN = 0x0a  # green.
FOREGROUND_RED = 0x0c  # red.
FOREGROUND_YELLOW = 0x0e  # yellow.

# 背景顏色定義 background colors
BACKGROUND_YELLOW = 0xe0  # yellow.

# 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)


# green
def printGreen(mess):
    set_cmd_text_color(FOREGROUND_GREEN)
    sys.stdout.write(mess + '\n')
    resetColor()


# red
def printRed(mess):
    set_cmd_text_color(FOREGROUND_RED)
    sys.stdout.write(mess + '\n')
    resetColor()


# yellow
def printYellow(mess):
    set_cmd_text_color(FOREGROUND_YELLOW)
    sys.stdout.write(mess + '\n')
    resetColor()


# white bkground and black text
def printYellowRed(mess):
    set_cmd_text_color(BACKGROUND_YELLOW | FOREGROUND_RED)
    sys.stdout.write(mess + '\n')
    resetColor()

使用


printGreen("你好,世界!")

順便把圖形放出來,供大家使用


replyContent = u'''' 
                _
               (\\  _                      ___
              .-"`"(\\                _.""`   `"-.
             /      ` `-._        _.-"            `\__
            6   6)        `-.__.-'                    `",
           /                                         `;-`
          /     ,                                     |
         ()    /  /`                                  |
          `---`"~``\                                  |
                    \                                 |
                     \            \      /           /
                     /`,   ,      |     |           /
                    /   "-.|      |     |         /'
                   /     / |     /,__   |       /`\ 
             ljs  /    /'  |    /    `"'\      (   \ 
               __/   /'    |   |         `\     \   \ 
               \    /      |   |           `\    \   \ 
                `-,/      /    |            /     |-"`
                         `"""^^^           `^^""""`

        ------------------------------------------------'''

printGreen(replyContent)

注意:測試在idea開發工具中打印使用未顯示彩色,但在Linux控制檯,cmd控制檯打均爲彩色字體。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章