一、问题描述
使用python编程时,改变控制台或终端中输出字体的颜色和格式,会显著提升代码质量,快速帮助我们定位问题和锁定重要输出。但是一般情况下,python控制台输出的字体默认为白色。具体如下:
在控制台打印很多相同的格式文字时,并不利于我们查找和定位想要的输出。
二、ansi转义序列
下面简单讲一下ansi转义序列,这里不重复讲述概念,想要了解ansi转义序列是什么意思,可自行查找。举个简单例子来说:
\033[31m
是一个ansi转义序列,它告诉终端将后续文本的颜色设置为红色;\033[0m
是另外一个ansi转义序列,它告诉终端将后续文本的颜色重置为默认颜色;
总之,ansi 转义序列是一种用于在控制台中输出格式化文本的标准,它由一系列以 esc
开头的字符组成,后跟一个或多个参数和一个字母,以指示需要执行的操作。常见的指令字母包括 m、h、j、k、s 和 u,常见的参数包括 0-8、30-37 和 40-47。
下面给出一些简单的指令参数:
指令字母 | 操作 |
---|---|
m | 设置文本属性 |
h | 设置光标属性 |
j | 清除屏幕 |
k | 清除行 |
s | 保存光标位置 |
u | 恢复光标位置 |
在参数中,分号用来分隔不同的参数,常见的参数包括:
参数 | 含义 |
---|---|
0 | 关闭所有属性 |
1 | 设置粗体 |
2 | 设置弱化(半亮) |
3 | 设置斜体 |
4 | 设置下划线 |
5 | 设置闪烁(慎用) |
7 | 设置反显 |
8 | 设置消隐 |
30-37 | 设置前景色(字体颜色) |
40-47 | 设置背景色 |
三、具体代码和显示效果(看懂这段代码,以后可随心控制字体的打印格式)
要在python中打印特定的字体格式或颜色(控制台,终端),可以通过上面的ansi转义序列来操作,下面给出设置前景色、设置背景色和设置显示方法的几种演示代码和效果,具体代码如下:
- 设置输出的前景色代码,也就是设置输出的显示字体代码:
# 输出前景色(字体颜色) print('-----------------------------------------------------') print('输出前景色(字体颜色):') print("\033[30m this text is foreground black.\033[0m") print("\033[31m this text is foreground red.\033[0m") print("\033[32m this text is foreground green.\033[0m") print("\033[33m this text is foreground yellow.\033[0m") print("\033[34m this text is foreground blue.\033[0m") print("\033[35m this text is foreground magenta.\033[0m") print("\033[36m this text is foreground cyan.\033[0m") print("\033[37m this text is foreground white.\033[0m")
具体效果如下:
- 设置输出的背景色代码:
# 输出背景色 print('-----------------------------------------------------') print('输出背景色:') print("\033[40m this text is background black.\033[0m") print("\033[41m this text is background pink-red.\033[0m") print("\033[42m this text is background dark-green.\033[0m") print("\033[43m this text is background yellow-red.\033[0m") print("\033[44m this text is background light-blue.\033[0m") print("\033[45m this text is background pink.\033[0m") print("\033[46m this text is background light-green.\033[0m") print("\033[47m this text is background grey color.\033[0m")
具体效果如下:
- 设置输出的显示方式代码,具体如下:
# 输出显示方式 print('-----------------------------------------------------') print(" this text is default.") # 默认白色 print("\033[0m this text is default.\033[0m") # 默认值 print("\033[1m this text is bold.\033[0m") # 加粗 print("\033[4m this text is underline.\033[0m") # 下划线 print("\033[5m this text is flicker.\033[0m") # 闪烁 print("\033[7m this text is reverse display.\033[0m") # 反显 # 前面加上2就是非xx print("\033[22m this text is non bold.\033[0m") # 非粗体 print("\033[24m this text is non underline.\033[0m") # 非下划线 print("\033[25m this text is non flicker.\033[0m") # 非闪烁 print("\033[7m this text is non reverse display.\033[0m") # 非反显
具体效果如下:
其他的组合方式可以自行探索,通过组合不同的ansi命令,即可获得不同的显示效果。
到此这篇关于利用python来控制终端打印字体的颜色和格式的文章就介绍到这了,更多相关python终端字体颜色和格式内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论