How to erase the characters output by Python

Code to erase the current line

del_line.py


import sys
sys.stdout.write("\033[2K\033[G")
sys.stdout.flush()

Example of use

sample.py


import sys, time

for i in range(10):
    s = str(i)*(10-i)
    sys.stdout.write("\033[2K\033[G%s" % s)
    sys.stdout.flush()
    time.sleep(0.5)
print()

The next output is displayed on the same line every 0.5 seconds, erasing the previous output.

0000000000
111111111
22222222
3333333
444444
55555
6666
777
88
9

Commentary

You can use something called CSI to control the console screen for standard output and error output. Reference: https://en.wikipedia.org/wiki/ANSI_escape_code In addition to erasing characters, you will be able to move the cursor and change the color of characters.

The second line \ 033 [2K of del_line.py corresponds to" EL – Erase in Line "in CSI Codes of the above Wiki, and it is a command to delete the line with the cursor. Whenever you use CSI with the message that \ 033 [ will use CSI, it will be output first. The following 2 corresponds to the argument.

--Erase from cursor position to end of line if 0 or omitted --If 1, delete from the beginning of the line to the cursor position --If 2, delete the line with the cursor

It will be. del_line.py erases the entire line. The final K determines the type of CSI.

As explained in the Wiki, "EL – Erase in Line" does not change the cursor position, so if you want to output characters after the erased line, you need to manually move the cursor to the beginning of the line. There is. This can be achieved using "CHA – Cursor Horizontal Absolute". The explanation on the Wiki says "Moves the cursor to column n (default 1)", so if you output the CSI code with n set to 1 or omitted, the cursor will move to the first column (the beginning of the line). The CSI code is CSI n G, so replace the CSI part with \ 033 [ to make it \ 033 [G.

Originally, I would like the characters to disappear as they are, but in Python, when outputting characters, it is saved in the buffer once and output at once at the time of line break. Therefore, even if you intend to output the CSI code for erasing characters on the source code, it will not be reflected on the actual screen. Therefore, sys.stdout.flush () explicitly outputs the character string stored in the buffer and reflects it on the screen.

With the above, the characters output to the console can be erased.

When erasing only one character

print("abc\033[1D\033[K")

Output result

ab

\ 033 [1D moves the cursor to the left, and \ 033 [K deletes from the cursor to the end of the line.

Supplement

--If the length of the character strings to be displayed continuously is the same, or if the subsequent output is longer, you can overwrite it by simply moving the cursor to the beginning of the line without the erase command. --"EL – Erase in Line" erases the line where the cursor is, so if you have a newline at the end of the previous output, use "CUU – Cursor Up" or "CPL – Cursor Previous Line" to move the cursor. You need to move up one level. --When you redirect the output to a file, the CSI code is recorded in the file. Therefore, it is very difficult to read with an editor etc., but you can reproduce the actual display by outputting it to the console with the cat command etc. --Since CSI code is not limited to Python, you can control the console in the same way by outputting the same CSI code in other programming languages and shell scripts.

Recommended Posts

How to erase the characters output by Python
[Python] How to output the list values in order
How to get the Python version
[Python] How to import the library
How to overwrite the output to the console
How to switch the configuration file to be read by Python
How to erase Python 2.x on Mac.
How to get colored output to the console
How to use the C library in Python
How to install Python
[Python] How to change the date format (display format)
[Algorithm x Python] How to use the list
How to get the files in the [Python] folder
[Python] How to sort instances by instance variables
How to output "Ketsumaimo" as standard output in Python
[Python] How to handle Japanese characters with openCV
How to automatically notify by phone when the python system is down
[CentOS8] How to output Python standard output to systemd log
How to sort by specifying a column in the Python Numpy array.
How to read all the classes contained in * .py in the directory specified by Python
[python] How to sort by the Nth Mth element of a multidimensional array
[Python] How to remove duplicate values from the list
How to retrieve the nth largest value in Python
How to get the variable name itself in python
Think about how to program Python on the iPad
How to get the number of digits in Python
[Introduction to Python] How to iterate with the range function?
How to know the current directory in Python in Blender
[Reintroduction to python] How to import via the parent directory
How to use the Raspberry Pi relay module Python
[python] option to turn off the output of click.progressbar
[Python] How to specify the download location with youtube-dl
Read the xml file by referring to the Python tutorial
How to eliminate garbled characters in matplotlib output image
[Python] How to use the graph creation library Altair
How to check the Java version used by Maven
Shift the alphabet string by N characters in Python
[Introduction to Udemy Python3 + Application] 27. How to use the dictionary
How to save a table scraped by python to csv
[Introduction to Udemy Python3 + Application] 30. How to use the set
[Python] Summary of how to specify the color of the figure
How to use the model learned in Lobe in Python
[Introduction to Python] How to stop the loop using break?
[Python] How to rewrite the table style with python-pptx [python-pptx]
How to enjoy Python on Android !! Programming on the go !!
How to unprefix the DB name used by pytest-django
How to install Python [Windows]
python3: How to use bottle (2)
How to use the generator
How to update Python Tkinter to 8.6
How to use Python argparse
[Python] How to use checkio
How to run Notepad ++ Python
How to change Python version
How to develop in Python
[python] How to judge scalar
[Python] How to use input ()
How to use the decorator
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)