Python log output different color fonts and print to the log file

Whether it is the client or the server, there are always a lot of logs being printed, and it is not easy to find the key ones. I investigated the method of printing log with color in Python. It should be the easiest. It does not require any external libraries, and it is supported by Windows and Linux.

Instructions

Enter the Python command line, execute os.system('')it at the program entrance , and then insert a few special characters on both sides of the character you want to print.

Here, it \033is 27 in octal, which is Escape in ASCII. [31mIt means that the things in the back turn red, and it [0mmeans that the things in the back are restored to default. [32mIt means that the things in the back turn green, and it [0mmeans that the things in the back are restored to their defaults.

It should be noted that when the program starts to execute, it must be executed os.system(''), that is, an empty cmd command is executed. If it is not executed, the color instruction will not be recognized.

Basic color

Think of it \033[31m as \033[3xm, the value range of x inside is from 0 to 7, which correspond to

The picture above is on Wikipedia, you can find it by searching "ansi escape code".

https://en.wikipedia.org/wiki/ANSI_escape_code​en.wikipedia.org

 

After encapsulating it, you can print the log with colors at will!

principle

These are the ANSI escape codes, which are explained in detail on the encyclopedia page above. Why is "escape"? It's the octal \033 here, which is decimal 27, which is hexadecimal 0x1B, which is Esc in ASCII. Another search keyword is VT100 Emulation.

In other words, Console can not only output original characters, but also change the format of characters, and even manipulate cursors.

Other methods of use

Can I directly echo a colored string in cmd? Of course you can, but you have to learn to enter Escape characters. My test must be cmd, not Powershell.

How to enter escape? There seem to be two kinds. In the first type, press 27 while holding down Alt, and then release Alt; in the second type, press Ctrl+[.

Although a ^[ is displayed, it is not possible to directly enter a ^[.

Can it be in a text file? Although you cannot view it directly with an editor, it is also possible if you print it to the command line.

Open Notepad++, enter

How to input this ESC? Find a ready-made copy, or press and hold Alt, press 27, release Alt, and an ESC will come out! Other control characters in ASCII can also be entered in this way.

Then you can print in the command line

If you write directly in a batch file, you can also echo colored characters like this.

Other formats

Carefully study the articles on the wiki. There are many other formats. I just mentioned the [3xmforeground color, and [4xmthe background color, which [9xmis the bright foreground color and [10xmthe bright background color.

Here is a script that prints all 32 combinations of these 4 patterns * 8 colors.

class Color:
    Black = 0
    Red = 1
    Green = 2
    Yellow = 3
    Blue = 4
    Magenta = 5
    Cyan = 6
    White = 7

class Mode:
    Foreground = 30
    Background = 40
    ForegroundBright = 90
    BackgroundBright = 100

def tcolor(c, m=Mode.Foreground):
    return '\033[{}m'.format(m + c)

def treset():
    return '\033[0m'

if __name__ == '__main__':
    import os
    os.system('')

    # usage
    print(tcolor(Color.Red) + 'hello' + treset())
    print(tcolor(Color.Green, Mode.Background) + 'color' + treset())
    print()

    COLOR_NAMES = ['Black', 'Red', 'Green', 'Yellow', 'Blue', 'Magenta', 'Cyan', 'White']
    MODE_NAMES = ['Foreground', 'Background', 'ForegroundBright', 'BackgroundBright']

    fmt = '{:11}' * len(COLOR_NAMES)
    print(' ' * 20 + fmt.format(*COLOR_NAMES))

    for mode_name in MODE_NAMES:
        print('{:20}'.format(mode_name), end='')
        for color_name in COLOR_NAMES:
            mode = getattr(Mode, mode_name)
            color = getattr(Color, color_name)
            print(tcolor(color, mode) + 'HelloColor' + treset(), end=' ')
        print()
 

Output in VSCode console

Output in Powershell

Output in cmd

Output in raspbian

As said in the wiki, the actual RGB value corresponding to each color may be different for different consoles.

In fact, there are various formats such as highlight, cross out, underline, etc. You can study the wiki carefully, or look at a script here

win10colors.cmd

https://stackoverflow.com/questions/2048509/how-to-echo-with-different-colors-in-the-windows-command-line​stackoverflow.com

 

Below is the output of the first few lines of this win10colors.cmd, bold and underlined.

Different consoles may not fully support all functions.

Why do we need os.system('')

If this sentence is omitted, the color command under Windows will not take effect. In fact, the side effect of this sentence is used. The side effect is that when cmd is executed, the VT100 simulation will be opened. In fact, a more "correct" approach is to use the SetConsoleMode provided by Windows.

How to use the new support for ANSI escape sequences in the Windows 10 console?​stackoverflow.comicon

Linux does not need this os.system('')

If you are interested, you can find out how libraries such as IPython start this VT100 simulation.

other

The print may be overwritten, or several packages print_info, print_warning, print_error functions and the like.

Or everyone can use their own print function. For example wyh_print, you can freely switch everyone's log locally and add colors to yourself without affecting others.

If it can be combined with logging and configure different levels, the colors of logs of different modules will be great.

Main reference

 

https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python​stackoverflow.com

 

https://stackoverflow.com/questions/2048509/how-to-echo-with-different-colors-in-the-windows-command-line​stackoverflow.com

 

https://en.wikipedia.org/wiki/ANSI_escape_code​en.wikipedia.org

 

https://docs.microsoft.com/en-us/windows/console/setconsolemode?redirectedfrom=MSDN#ENABLE_VIRTUAL_TERMINAL_PROCESSING​docs.microsoft.com

 

Bonus

The piles mentioned above are not effective in IDLE, but it is true that various colors can be output in IDLE. I forgot where I copied it, but the following code can print color characters in IDLE

import sys

try:
    shell = sys.stdout.shell
except AttributeError:
    raise RuntimeError("you must run this program in IDLE")

shell.write("Wanna go explore? ","KEYWORD")
shell.write("OPTIONS","STRING")
shell.write(" : ","KEYWORD")
shell.write("Yes","DEFINITION")
shell.write(" or ","KEYWORD")
shell.write("No","COMMENT")

print()
print("here are all the valid tags:\n")

valid_tags = ('SYNC', 'stdin', 'BUILTIN', 'STRING', 'console', 'COMMENT', 'stdout',
              'TODO','stderr', 'hit', 'DEFINITION', 'KEYWORD', 'ERROR', 'sel')

for tag in valid_tags:
    shell.write(tag+"\n",tag)
    

Output in IDLE

 

Posted on 2020-04-25

Guess you like

Origin blog.csdn.net/xcntime/article/details/115016933