How does python output color-coded text in linux?

Source: Internet
Author: User

During the development project, some logs are often output to stdout to facilitate code debugging. By default, these logs are directly displayed on the terminal. Some notices of common application servers, third-party libraries, and even servers will be displayed on the terminal, which will disrupt the information we want.

We can set different colors for useful information to achieve striking results, because I usually develop them in linux, and the colors in linux terminals are controlled by escape sequences, the escape sequence starts with ESC and can be used to complete the same work with \ 033 (the ASCII code of ESC is expressed in decimal format as 27, which is equal to 33 in octal format ).

Description:

Copy codeThe Code is as follows:
Format: \ 033 [display mode; foreground color; background color m
 
Note:
Foreground color background color
---------------------------------------
30 40 black
31 41 red
32 42 green
33 43 colors
34 44 blue
35 45 purple red
36 46 blue
37 47 white
Display Method meaning
-------------------------
0 terminal default settings
1 highlighted
4. Underline
5 flashes
7. Reverse display
8 invisible
 
Example:
\ 033 [1; 31; 40 m <! -- 1-highlight 31-foreground color red 40-background color black -->
\ 033 [0 m <! -- Use the terminal default settings to cancel the color settings -->


The following is how I use python:
Copy codeThe Code is as follows: print '\ 033 [1; 31; 40m'
Print '* 50
Print '* HOST: \ t', request. META. get ('remote _ ADDR ')
Print '* URI: \ t', request. path
Print '* ARGS: \ t', QueryDict (request. body)
Print '* TIME: \ t', time. time ()-request. start_time
Print '* 50
Print '\ 033 [0m'

As follows:


Of course, this is only a simple implementation method, and only works in linux. You can use termcolor in other ways, or refer to the ipython console implementation (pyreadline ).

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.