Python colorama | Explain how to achieve beautiful color printing in the terminal


I. Introduction

Building a command line program is cool: the command line can do what we want it to do without spending a lot of time designing a GUI interface compared to a GUI interface program. But to make the command line program more attractive, it is impossible to do it with just the normal print function.

A good solution is to use the colorama library. This allows us to colorize strings output on the terminal very easily and improve the appearance of the program's interface.

Without further ado, let's see how to use it!

The character color of the terminal is controlled by the escape sequence, which is the system display function in text mode and has nothing to do with the specific language. The escape sequence starts with ESC, which is completed with \033 (the ASCII code of ESC is 27 in decimal, and it is in octal 033).

Writing format:

  • Beginning part : \033[Display mode;Foreground color;Background color m + Ending part:\033[0m
  • Note : The three parameters at the beginning: display mode, foreground color, and background color are optional parameters, and you can write only one of them; in addition, because the values ​​representing the different meanings of the three parameters are unique and not repeated, the three parameters There is no fixed requirement for the writing sequence of each parameter, and the system can recognize it; however, it is recommended to write according to the default format specification.
  • For the ending part : it can be omitted, but in order to write the specification, it is recommended to start with \033[*** and end with \033[0m.

The meaning of the parameter represented by the numerical value:

  • Display mode : 0 (default), 1 (highlighted), 22 (not bold), 3 (italic), 4 (underlined), 24 (not underlined), 5 (flashing), 25 (non-flashing), 7 (reverse display), 27 (non-reverse display)
  • Foreground color (color of the font ): 30 (black), 31 (red), 32 (green), 33 (yellow), 34 (blue), 35 (magenta), 36 (cyan), 37 (white)
  • Background Color : 40 (black), 41 (red), 42 (green), 43 (yellow), 44 (blue), 45 (magenta), 46 (cyan), 47 (white)

Second, print color printing

For example, the string \033[31m represents red printing, and the string \033[0m is used to set the terminal's color to the standard default color (usually black). The sample code is as follows:

begin_color = '\033[1;31m'
end_color = '\033[0m'
print(begin_color + "人生苦短,我用Python!" + end_color)
print("人生苦短,我用Python!")

You can flexibly set the display mode , foreground color (font color), and background color . According to your own needs, it is more convenient to encapsulate the commonly used ones and call them directly when using them.

Please add image description

class printColors:
    RED = "\033[1;31m"       # 红色
    RED_3 = "\033[4;31m"     # 红色  带下划线
    PURPLE = "\033[1;35m"    # 紫色
    CYAN = "\033[1;36m"      # 青蓝色
    END = '\033[0m'

print(":".join(["CSDN叶庭云", "https://yetingyun.blog.csdn.net/"]))
print(printColors.CYAN + "人生苦短,我用Python!" + printColors.END)
print(printColors.RED + "人生苦短,我用Python!" + printColors.END)
print(printColors.RED_3 + "人生苦短,我用Python!" + printColors.END)
print(printColors.PURPLE + "人生苦短,我用Python!" + printColors.END)


3. Use the Colorama library

You can also use the Colorama library in Python to change the color, brightness, and background of the terminal output text.

Colorama Pypi

The implementation behind this library is also very simple, it uses ANSA escape character sequences. When the terminal reads one of these sequences, it doesn't output. When the terminal is indicated as the next output it uses the previously set color for the corresponding output.

The first is to install, use pip to install directly, the command line is as follows:

pip install colorama -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

After the installation is complete, then we can start practicing. It is good programming practice to add the following initialization code at the beginning of the code (this is used to ensure that the Windows command line handles the ANSA string sequence correctly. Otherwise, it will just print out the character sequence):

If you are using another operating system, the init() function will do nothing at this point, but it is recommended that you should still explicitly put it in our program to ensure that our program will work on any platform .

Now we can start using the library. Mainly divided into three subcategories:

  • Fore : used to change the color of the output text;
  • Style : used to change the brightness of the output text;
  • Back : Used to change the background of the output text (i.e. the highlighted text).

Then we can start by changing the color of the text, Colorama allows us to use 8 88 different colors: black, red, green, yellow, blue, magenta, cyan, white. They are implemented as variables in the Fore class. Their names are the names of the colors, all caps. E.g:

from colorama import Fore, init

init()
print('人生苦短,我用Python!')
print(":".join(["CSDN叶庭云", "https://yetingyun.blog.csdn.net/"]))
print(Fore.RED + '人生苦短,我用Python!')
print(Fore.BLUE + '人生苦短,我用Python!')
print(Fore.GREEN + '人生苦短,我用Python!')
print(Fore.MAGENTA + '人生苦短,我用Python!')
print(Fore.RESET + '人生苦短,我用Python!')   # 回归初始

The above code is easy to implement, as we can see, we also use another variable RESET, which is mainly used to restore the original color of the text.

The class we will introduce next is Back, which implements the same nine keywords as the Fore class: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.

Now in this background, the set color will be used to change the background of the output text (i.e. the highlighted text). An example is as follows:

from colorama import Fore, Back, init

init()
print('人生苦短,我用Python!')
print(":".join(["CSDN叶庭云", "https://yetingyun.blog.csdn.net/"]))
print(Back.RED + '人生苦短,我用Python!')
print(Back.BLUE + '人生苦短,我用Python!')
print(Back.GREEN + '人生苦短,我用Python!')
print(Back.MAGENTA + '人生苦短,我用Python!')
print(Back.RESET + '人生苦短,我用Python!')   # 回归初始


Finally, we can use the Style class to change the brightness of the output text. This subclass contains the following three main keywords:

  • BRIGHT: make the output text brighter
  • DIM: Dim the output text (although it looks the same as normal text)
  • NORMAL: yes output text becomes normal brightness

A simple example is as follows:

from colorama import Style, init

init()
print('人生苦短,我用Python!')
print(Style.BRIGHT + '人生苦短,我用Python!')
print(Style.DIM + '人生苦短,我用Python!')

Reference:


Guess you like

Origin blog.csdn.net/fyfugoyfa/article/details/122778172