Is it possible to manipulate lines of text that have already been printed to the console?
For example,
import time
for k in range(1,100):
print(str(k)+"/"+"100")
time.sleep(0.03)
#>> Clear the most recent line printed to the console
print("ready or not here I come!")
I've seen some things for using custom DOS consoles under Windows, but I would really like something that works on the command_line like does print without any additional canvases.
Does this exist? If it doesn’t, why not?
P.S.: I was trying to use curses, and it was causing problems with my command line behaviour outside of Python. (After erroring out of a Python script with curses in it, my Bash shell stopped printing newline -unacceptable- ).
Summary: The most straightforward way to overwrite the previous print to stdout is to set the carriage return ( '\r' ) character within the print statement as print(string, end = "\r") . This returns the next stdout line to the beginning of the line without proceeding to the next line.
In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.
What you're looking for is:
print("{}/100".format(k), "\r", end="")
\r
is carriage return, which returns the cursor to the beginning of the line. In effect, whatever is printed will overwrite the previous printed text. end=""
is to prevent \n
after printing (to stay on the same line).
A simpler form as suggested by sonrad10 in the comments:
print("{}/100".format(k), end="\r")
Here, we're simply replacing the end character with \r
instead of \n
.
In Python 2, the same can be achieved with:
print "{}/100".format(k), "\r",
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With