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