[python3]:python3——在命令行中输出有颜色的文本
一、 python3在命令行中输出有颜色文本的原理
1. ANSI转义序列: 在python3的【print】函数中,嵌入颜色控制代码【 \033[30~37m 这里替换成自己的文字 \033[0m 】
\033[30-37m 设置前景色(黑/红/绿/黄/蓝/紫/青/白)
\033[40-47m 设置背景色(同上色系)
组合用法示例: \033[47;31m \033[0m (白底红字)
二、 代码实例
[wit@ubuntu:tmp]$ cat print_with_color
#!/usr/bin/env python3
def print_with_color():
g = ( f"color_{i}" for i in range(10) )
print(f"\n")
for line in g:
#print(f"\033[32m TEXT_POSITION \033[0m")
print(f"\033[32m\t[out]#\t{line}\033[0m")
print(f"\n")
if __name__ == '__main__' :
print_with_color()
[wit@ubuntu:tmp]$
[wit@ubuntu:tmp]$
[wit@ubuntu:tmp]$ ./print_with_color
[out]# color_0
[out]# color_1
[out]# color_2
[out]# color_3
[out]# color_4
[out]# color_5
[out]# color_6
[out]# color_7
[out]# color_8
[out]# color_9
[wit@ubuntu:tmp]$
[wit@ubuntu:tmp]$
2. 图片展示

三、 参考资料
1. [c/cpp]:ANSI转义序列(终端显示) -- https://www.cnblogs.com/lnlidawei/p/19056188
.
本文由 lnlidawei 原创、整理、转载,本文来自于【博客园】; 整理和转载的文章版权归属【原创作者】; 转载或引用时【请保留文章的来源信息】:https://www.cnblogs.com/lnlidawei/p/19065464

浙公网安备 33010602011771号