Python Tips-Terminal Screen Printing Cursor and Text Control

Python Tips-Terminal Screen Printing Cursor and Text Control

In the terminal, how to control the cursor output position and the output font color? Since the default is always a single color, white text on a black background, but in some scenarios it does not meet the output needs well, such as in large and fast output, the output For some prompt or warning information, ordinary white text output on a black background may or may not be effective.

This article will introduce how to control the cursor position and font color output to the terminal interface.

ANSI escape sequence

The terminal can do more than just display the output of a program. It can display a moving cursor, color text, clear the entire screen, and do more than just static output. Such as color fonts or blinking cursors or progress bars.

Change the output behavior of the terminal by using a special output string. The simplest example is the newline example: \n

escape sequence syntax

The syntax format is as follows:

Escape character style;

转义字符
样式

Escape characters: \033[ or \x16[ or \u001b[

Separator: ; (semicolon)

Cursor control

code meaning
\033[nA Move cursor up n lines
\033[nB Move cursor down n lines
\033[nC Move cursor right n lines
\033[nD Move cursor left n lines
\033[y;xH Cursor coordinates (x,y)
\033[2J clear screen
\033[K Clear from cursor to end of line
\# 将光标移动到第10行第20列的位置
print('\033[10;20H')

\# 将光标向上移动5print('\033[5A')

\# 将光标向下移动3print('\033[3B')

\# 将光标向右移动4print('\033[4C')

\# 将光标向左移动2print('\033[2D')

escape character

Escape characters can have three forms

Hexadecimal:\x16[

Unicode:\u001b[

Octal:\033[

style

This style refers to the display style of the font:

0 (default), 1 (highlight), 22 (non-bold)

4 (underline), 24 (non-underline), 5 (flashing)

25 (non-flash), 7 (reverse display), 27 (non-reverse display)

coloring scheme

There are two color schemes widely used in terminals:

  • 16 colors (8 background + 8 foreground), the foreground is the color of the font itself
  • 255 colors

16 colors

The 16-color color scheme contains two color settings, each with 8 colors, one is the background color and the other is the font color (that is, the foreground color).

分号
分号
转义字符
样式
文字颜色
背景颜色
m

Escape characters: \033[ or \x16[ or \u001b[

Separator: ; (semicolon)

Ending character: m


As an example:

\033[1;32;40m

Here \033[ is the escape character 1 represents highlighting, 32 represents the foreground color is green and the background color is black

Style test statement:

print('\033[0;32;40m这是一行测试字体\033[0m')  
print('\033[1;32;40m这是一行测试字体\033[0m')  
print('\033[22;32;40m这是一行测试字体\033[0m')  
print('\033[4;32;40m这是一行测试字体\033[0m')  
print('\033[24;32;40m这是一行测试字体\033[0m')  
print('\033[5;32;40m这是一行测试字体\033[0m')  
print('\033[25;32;40m这是一行测试字体\033[0m')  
print('\033[7;32;40m这是一行测试字体\033[0m')  
print('\033[27;32;40m这是一行测试字体\033[0m')  

It should be noted that the specific effect may be limited by the terminal used. Currently, the output in CMD will not be recognized, but in the window terminal, the above content is successfully output.

Color settings

Foreground color: 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)

Foreground color, that is, the display of font color:

print('\033[1;30;40m这是一行黑色测试字体\033[0m')  
print('\033[1;31;40m这是一行红色测试字体\033[0m')  
print('\033[1;32;40m这是一行绿色测试字体\033[0m')  
print('\033[1;33;40m这是一行黄色测试字体\033[0m')  
print('\033[1;34;40m这是一行蓝色测试字体\033[0m')  
print('\033[1;35;40m这是一行洋红测试字体\033[0m')  
print('\033[1;36;40m这是一行青色测试字体\033[0m')  
print('\033[1;37;40m这是一行白色测试字体\033[0m')  

Background color:

print('\033[1;37;40m这是一行黑色测试背景\033[0m')  
print('\033[1;37;41m这是一行红色测试背景\033[0m')  
print('\033[1;37;42m这是一行绿色测试背景\033[0m')  
print('\033[1;37;43m这是一行黄色测试背景\033[0m')  
print('\033[1;37;44m这是一行蓝色测试背景\033[0m')  
print('\033[1;37;45m这是一行洋红测试背景\033[0m')  
print('\033[1;37;46m这是一行青色测试背景\033[0m')  
print('\033[1;37;47m这是一行白色测试背景\033[0m')  

Colorama is a color output module

It is very troublesome to need such configuration for every input and output. Colorama provides convenient configuration of font color output.

from colorama import init, Fore, Back, Style  

# Initializes Colorama  
init(autoreset=True)  

print(Style.BRIGHT + Back.YELLOW + Fore.RED + "from colorama import init, Fore, Back, Style  

# Initializes Colorama  
init(autoreset=True)  

print(Style.BRIGHT + Back.YELLOW + Fore.RED + "Colorama ")")  

Simple color changing function

background_color_dict={
    
      
    'BLACK':40,  
    'RED':41,  
    'GREEN':42,  
    'YELLOW':43,  
    'BLUE':44,  
    'MAGENTA':45,  
    'CYAN':46,  
    'WHITE':47  
}  

text_color_dict={
    
      
    'BLACK':30,  
    'RED':31,  
    'GREEN':32,  
    'YELLOW':33,  
    'BLUE':34,  
    'MAGENTA':35,  
    'CYAN':36,  
    'WHITE':37  
}  

style_dict={
    
      
    'normal':0,  
    'bold':1,  
    'light':2,  
    'italicize':3,  
    'underline':4,  
    'blink':5  
}  

def set_text_color(str_text, style, text_color, background_color):  
    str = str_text  
    style_code = style_dict[style]  
    text_color_code = text_color_dict[text_color]  
    back_color_code = background_color_dict[background_color]  
    print_text = f'\033[{
      
      style_code};{
      
      text_color_code};{
      
      back_color_code}m{
      
      str}\033[0m'  
    return print_text  

256 colors

The output syntax format of 256 colors is a little different from that of 16 colors. The escape character remains unchanged, and the label display mode is 38 or 48. Select whether the color code behind a table name is the foreground color or the background color.

分号
分号
5
转义字符
前景38/背景48
前景/背景颜色代码
m

If you want to modify it at the same time, set the foreground and background twice respectively, and then display the character sequence. Such as statement:

print("\033[48;5;160m\033[38;5;231m背景前景修改ABCDE \033[38;5;226m前景修改ABCDE\033[0;0m")  

Output all the foreground colors

def print_colors_256(color_code):  
    num1 = str(color_code)  
    num2 = str(color_code).ljust(3, ' ')  
    if color_code % 16 == 0:  
        return(f"\033[38;5;{
      
      num1}m {
      
      num2} \033[0;0m\n")  
    else:  
        return(f"\033[38;5;{
      
      num1}m {
      
      num2} \033[0;0m")  

print("256 color scheme:")  
print('',end=' ')  
print(' '.join([print_colors_256(x) for x in range(256)]))  

The display effect may be different, possibly because the terminal theme is different and the color code definition is different.
Insert image description here

Appendix 1: Color serial number

background color Font color
30: black 40: black
31:Red 41:Red
32:green 42:green
33:yellow 43:yellow
34: blue 44:Blue
35:Purple 45:Purple
36:green 46:green
37:White 47:White

Appendix 2: ANSI control code

code Effect
\033[0m Close all
\033 [1 m Highlight
\033[4m Underline
\033 [5 m flashing
\033[7m Reverse display
\033[8m blanking
\033[30m ~ \033[37m background color
\033[40m ~ \033[47m Font color
\033[nA Move cursor up n lines
\033[nB Move cursor down n lines
\033[nC Move cursor right n lines
\033[nD Move cursor left n lines
\033[y;xH Cursor coordinates (x,y)
\033[2J clear screen
\033[K Clear from cursor to end of line
\033[s & \033[u Save & restore cursor position
\033[25l & \033[25h Hide & show cursor

Guess you like

Origin blog.csdn.net/Alex_StarSky/article/details/83933170