Acralia
Acralia

Reputation: 23

delete current line in python with print

I'm executing code in python and want to update my status by rewriting the current line on the output. Example:

import time

print("1 a a a", end="\r")
time.sleep(1) #placeholder for doing stuff
print("2 a a a", end="\r")
time.sleep(1) #placeholder for doing stuff
print("3 a a a", end="\r")
time.sleep(1) #placeholder for doing stuff
print("BBBB")
print("c")

Now the output of this Code is

BBBBa a
c

How can I alter my code to have the following output?

BBBB
c

Thank you.

Upvotes: 2

Views: 1547

Answers (1)

chepner
chepner

Reputation: 531055

\r only moves the cursor; it doesn't delete text per se, it only provides the opportunity to overwrite existing text.

Pretty much anything you try will be terminal-dependent, but usually you are using one that uses ANSI escape sequences. One such sequence can be used to clear the current line.

import time

print("\x1b[K1 a a a", end="\r")
time.sleep(1) #placeholder for doing stuff
print("\x1b[K2 a a a", end="\r")
time.sleep(1) #placeholder for doing stuff
print("\x1b[K3 a a a", end="\r")
time.sleep(1) #placeholder for doing stuff
print("\x1b[KBBBB")
print("c")

\x1b[K clears from the current cursor position to the end of the current line.

Libraries like ncurses can be used for terminal-independent handling of the screen.

Upvotes: 2

Related Questions