Python Display color output

Source: Internet
Author: User

Cause

In the development of the project, in order to facilitate debugging code, often to stdout output some logs, the default of these logs are directly displayed in the terminal. And the general application server, third-party libraries, and even some of the server's announcements are also displayed in the terminal, which disturbs the information we want.

Solve

We can make eye-catching effect by setting different colors for useful information, because I usually develop under Linux, and the colors in Linux terminal are controlled by escape sequence, the escape sequence starts with ESC and can do the same work with \033 ( The ASCII code of ESC is expressed in decimal notation is 27, which equals 33 in octal notation.

The writing format, and the related instructions are as follows:

12345678910111213141516171819202122232425 格式:\033[显示方式;前景色;背景色m说明:前景色            背景色           颜色---------------------------------------30                40              黑色31                41              红色32                42              绿色33                43              黃色34                44              蓝色35                45              紫红色36                46              青蓝色37                47              白色显示方式           意义-------------------------0                终端默认设置1                高亮显示4                使用下划线5                闪烁7                反白显示8                不可见例子:\033[1;31;40m    <!--1-高亮显示 31-前景色红色  40-背景色黑色-->\033[0m          <!--采用终端默认设置,即取消颜色设置-->

Here's how I used it in Python:

12345678 print ‘\033[1;31;40m‘print ‘*‘ * 50print ‘*HOST:\t‘, request.META.get(‘REMOTE_ADDR‘)print ‘*URI:\t‘, request.pathprint ‘*ARGS:\t‘, QueryDict(request.body)print ‘*TIME:\t‘, time.time() - request.start_timeprint ‘*‘ * 50print ‘\033[0m‘

As follows:

Of course, this is just a simple implementation, and only valid under Linux, other ways can use Termcolor, or refer to the Ipython console implementation (Pyreadline).

Python Display color output

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.