lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

[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.  图片展示

image

 

 

 

三、  参考资料

 

  1.  [c/cpp]:ANSI转义序列(终端显示)  --  https://www.cnblogs.com/lnlidawei/p/19056188

 

  .

posted on 2025-08-30 07:31  lnlidawei  阅读(22)  评论(0)    收藏  举报