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