【python】控制台输出颜色

时间:2023-01-02 19:49:38

来源:http://www.cnblogs.com/yinjia/p/5559702.html

在开发项目过程中,为了方便调试代码,经常会向stdout中输出一些日志,默认的这些日志就直接显示在了终端中。而一般的应用服务器,第三方库,甚至服务器的一些通告也会在终端中显示,这样就搅乱了我们想要的信息。

书写格式,和相关说明如下:

【python】控制台输出颜色
 1 格式:\033[显示方式;前景色;背景色m
2
3 说明:
4 前景色 背景色 颜色
5 ---------------------------------------
6 30 40 黑色
7 31 41 红色
8 32 42 绿色
9 33 43 黃色
10 34 44 蓝色
11 35 45 紫红色
12 36 46 青蓝色
13 37 47 白色
14 显示方式 意义
15 -------------------------
16 0 终端默认设置
17 1 高亮显示
18 4 使用下划线
19 5 闪烁
20 7 反白显示
21 8 不可见
22
23 例子:
24 \033[1;31;40m <!--1-高亮显示 31-前景色红色 40-背景色黑色-->
25 \033[0m <!--采用终端默认设置,即取消颜色设置-->
【python】控制台输出颜色

举例:

【python】控制台输出颜色
1 print('\033[1;31;40m')
2 print('*' * 50)
3 print('*HOST:\t', 2002)
4 print('*URI:\t', 'http://127.0.0.1')
5 print('*ARGS:\t', 111)
6 print('*TIME:\t', '22:28')
7 print('*' * 50)
8 print('\033[0m')
【python】控制台输出颜色

运行结果:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAksAAADICAIAAAB3ZDIKAAAPaUlEQVR4nO3dP3KjzLoH4F7LSe5NnEygqpnZg5dwFDnWFr5Mkcr78CX1FnwyFjCrsFcwN+BIbuimQYD/tZ+nuqZm0AtIqq94vx80KPzP//4rOwIAfGldP/vnn390OACqIsMBUCcZDoA6yXAA1EmGA6BOMhwAdZLhAKiTDAdAnWQ4AOokwwFQJxkOgDrJcADUSYYDoE4yHAB1kuEAqJMMB0Cd5mS4XQgvITyPb0SBAgUKFCjYpGBLczLcZ/jMChQoUKDgOxRsqZDhmhBeQmhDCCG8hNCEEEJoo78rUKBAgQIFmxS8iUKGO4bwEsJzCMcQ2vOflyUKFChQo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+uGbqzUwWTL7bmVvwXEqAaX5bINvh1twkB8Cn4PfhAKiTDAdAnWQ4AOokwwFQJxkOgDrJcADUSYYDoE4yHAB1kuEAqJMMB0CdZDgA6iTDAVAnGQ6AOslwANRJhgOgTjIcAHWS4QCo05wMtwvhJYTn8Y0oUKBAgQIFmxRsaU6G+wyfWYECBQoUfIeCLRUyXBPCSwhtCCGElxCaEEIIbfR3BQoUKFCgYJOCN1HIcMcQXkJ4DuEYQnv+87JEgQIFChQo2KrgTUxeh+sS5cv5reySLShQoECBAgWbFGxs8jrcZ/jMChQoUKDgOxRsrJDhBqGynUqdChQoUKBAwbKCN1HIcIMLg88hDBYqUKBAgQIFmxS8iavuh9uPbESBAgUKFCjYpGBLV90P95m/FAUKFChQUEHBljyXEoA6eS4lAHWS4QCokwwHQJ1kOADqJMMBUCcZDoA6yXAA1GkswxmGYRjGlx6jGc4wDMMwvvSQ4QzDMIw6hwxnGIZh1DlkOMMwDKPOIcMZhmEYdQ4ZzjAMw6hzyHCGYRhGnUOGMwzDMOocMpxhGIZR55DhDMMwjDqHDGcYhmHUOWQ4wzAMo84hwxmGYRh1DhnOMAzDqHP8P4efAuND+IsRAAAAAElFTkSuQmCC" alt="" />

注意:上面的\033是8进制的数字,转换十六进制就是\x1b,用print('\x1b[1;31;40m') 也是可以达到同样效果的。

作者:尹佳 出处:http://www.cnblogs.com/yinjia/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。