How does python output color-coded text in linux?

Source: Internet
Author: User
This article mainly introduces how to output color text in python in linux. it only works in Linux and is generally output in the console. This article is used in the log link to facilitate testing, for more information, see the following. 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:

The 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
\ 033 [0 m


The following is how I use python:

The 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.