简介
日常开发中,经常需要打印显示各种信息。海量的信息堆砌在控制台中,就会导致各种信息都显示在一起,降低了重要信息的可读性。这时候,如果能给重要的信息加上差异的字体颜色,那么就会更加显眼,增加使用者可阅读性。Colorama是一个python专门用来在控制台、命令行输出彩色文字的模块,可以跨平台使用。
字体打印的三种方式:
1、原生:推荐只处理一两句,临时使用的时候用原生。
2、colorama模块:使用的地方很多的时候,推荐使用这个,易读性更高。
3、termcolor模块:不推荐。
安装方式
pip install colorama pip install termcolor
原生方式打印:33[显示方式;字体色;背景色m…[33[0m
设置环境变量
| 前景色 | 背景色 | 颜色 | 
|---|---|---|
| 30 | 40 | 黑色 | 
| 31 | 41 | 红色 | 
| 32 | 42 | 绿色 | 
| 33 | 43 | 黃色 | 
| 34 | 44 | 蓝色 | 
| 35 | 45 | 洋红 | 
| 36 | 46 | 青色 | 
| 37 | 47 | 白色 | 
显示方式 意义
| 显示方式 | 意义 | 
|---|---|
| 0 | 终端默认设置 | 
| 1 | 高亮显示 | 
| 22 | 非高亮显示 | 
| 4 | 使用下划线 | 
| 24 | 去下划线 | 
| 5 | 闪烁 | 
| 25 | 去闪烁 | 
| 7 | 反白显示 | 
| 27 | 非反显 | 
| 8 | 不可见 | 
| 28 | 可见 | 
例如:
033[1;32;41m # 1-高亮显示 32-前景色绿色 40-背景色红色--- 33[0m # 采用终端默认设置,即缺省颜色---
显示颜色格式:33[显示方式;字体色;背景色m......[33[0m
书写格式:
开头部分:33[显示方式;前景色;背景色m   结尾部分:33[0m
解释:
开头部分的三个参数:显示方式,前景色,背景色是可选参数,可以只写其中的某一个;
由于表示三个参数不同含义的数值都是唯一的没有重复的,所以三个参数的书写先后顺序没有固定要求,系统都能识别;
建议按照默认的格式规范书写。
对于结尾部分,其实对后续输出信息的颜色样式定义,一般设置为系统默认,也可以省略,但是为了显示和书写规范,建议33[***开头,33[0m结尾。
案例源码
# -*- coding: utf-8 -*-
# time: 2022/10/3 10:30
# file: color.py
# 公众号: 玩转测试开发
import sys
from termcolor import colored, cprint
from colorama import Fore, Back, Style
def primal_print():
    # 通用格式:033[1;31m   mes   033[0m
    mes1 = "我是红色"
    print("\033[1;31m"   mes1   "\033[0m")
    mes2 = "我是绿色"
    print("\033[1;32m"   mes2   "\033[0m")
    # 组合的方式:如 下划线 - 红色字体 - 背景黑色
    mes3 = "我是组合的方式"
    print("\033[4;31;40m"   mes3   "\033[0m")
def termcolor_demo():
    text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
    print(text)
    cprint('Hello, World!', 'green', 'on_red')
    print_red_on_cyan = lambda x: cprint(x, 'red', 'on_cyan')
    print_red_on_cyan('Hello, World!')
    print_red_on_cyan('Hello, Universe!')
    for i in range(3):
        cprint(str(i), 'magenta', end=' ')
    print()
def color_demo():
    # 字体颜色
    print(Fore.RED   "甲是红色")
    print(Fore.GREEN   "乙是绿色")
    print(Fore.BLUE   "丙是蓝色")
    # 重置设置,还原默认设置
    print(Style.RESET_ALL)
    # 字体背景色
    print(Back.RED   "A的背景色为红色")
    print(Back.GREEN   "B的背景色为绿色")
    print(Back.BLUE   "C的背景色为蓝色")
    # 重置设置,还原默认设置
    print(Style.RESET_ALL)
    # 字体加粗
    print(Style.BRIGHT   "字体加粗")
    # 组合
    print(Fore.RED   Back.GREEN   Style.BRIGHT   "绿底红字加粗")
    # 重置设置,还原默认设置
    print(Style.RESET_ALL   "普通字体")
if __name__ == '__main__':
    primal_print()
    print("*" * 80)
    termcolor_demo()
    print("*" * 80)
    color_demo()
执行结果:

本质上colorama和termcolor只是对源生的封装。
即:python打印终端字体格式,只处理一两句,临时使用的时候用源生,使用的地方很多的时候,推荐使用这个colorama模块,易读性更高。
以上就是详解Python如何在终端打印字体颜色的详细内容,更多关于Python终端打印字体颜色的资料请关注Devmax其它相关文章!