Python 如何给屏幕打印信息加上颜色

Python 如何给屏幕打印信息加上颜色

https://github.com/Textualize/rich

https://wxnacy.com/2019/04/24/python-print-color/

https://www.cnblogs.com/benjamin77/p/10853215.html

语法

print('\033[显示方式;字体色;背景色m文本\033[0m')
# 三种设置都可以忽略不写,都不写则为默认输出

配置如下

# 字体 背景 颜色
# ---------------------------------------
# 30  40  黑色
# 31  41  红色
# 32  42  绿色
# 33  43  黄色
# 34  44  蓝色
# 35  45  紫红色
# 36  46  青蓝色
# 37  47  白色
#
# 显示方式
# -------------------------
#  0  终端默认设置
#  1  高亮显示
#  4  使用下划线
#  5  闪烁
#  7  反白显示
#  8  不可见

举几个例子

# 高亮显示,字体紫红色,背景白色
text = 'Hello World'
print(f'\033[1;35;47m{text}\033[0m')

image

# 默认显示,字体紫红色,背景白色
text = 'Hello World'
print(f'\033[35;47m{text}\033[0m')

image

# 默认显示,字体紫红色,背景默认
text = 'Hello World'
print(f'\033[35m{text}\033[0m')

image

往往我们更关注字体颜色,几个字体颜色效果如下,我用的 iTerm2 的深色背景,效果会有点偏差
image

工具化

这个语法看起来还是很别扭的,平常使用我们可以封装起来。

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from enum import Enum

class Color(Enum):
    BLACK = 30
    RED = 31
    GREEN = 32
    YELLOW = 33
    BLUE = 34
    MAGENTA = 35
    CYAN = 36
    WHITE = 37

def print_color(text: str, fg: Color = Color.BLACK.value):
    print(f'\033[{fg}m{text}\033[0m')

# 打印红色文字
print_color('Hello World', fg = Color.RED.value)

偶然 发现有一个Python包, 可以完美解决这个问题

python colorama模块

colorama是一个python专门用来在控制台、命令行输出彩色文字的模块,可以跨平台使用。

  1. 安装colorama模块
pip install colorama

可用格式常数:

Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Style: DIM, NORMAL, BRIGHT, RESET_ALL

跨平台印刷彩色文本可以使用彩色光的常数简称ANSI转义序列:

from colorama import Fore,Back,Style
print (Fore.RED + "some red text")
print (Back.GREEN + "and with a green background")
print (Style.DIM + "and in dim text")
print (Style.RESET_ALL)
print ("back to normal now!!")

Init关键字参数:
init()接受一些* * kwargs覆盖缺省行为

init(autoreset = False):

如果你发现自己一再发送重置序列结束时关闭颜色变化每一个打印,然后init(autoreset = True)将自动化
示例:

from colorama import init,Fore
init(autoreset=True)
print (Fore.RED + "welcome to python !!")
print ("automatically back to default color again")
posted @ 2023-05-30 19:31  michaelchengjl  阅读(74)  评论(0编辑  收藏  举报