How can I overwrite/print over the current line in Windows command line?
Solution 1
yes:
import sys
import time
def restart_line():
sys.stdout.write('\r')
sys.stdout.flush()
sys.stdout.write('some data')
sys.stdout.flush()
time.sleep(2) # wait 2 seconds...
restart_line()
sys.stdout.write('other different data')
sys.stdout.flush()
Solution 2
I know this is old, but i wanted to tell my version (it works on my PC in the cmd, but not in the idle) to override a line in Python 3:
>>> from time import sleep
>>> for i in range(400):
>>> print("\r" + str(i), end="")
>>> sleep(0.5)
EDIT: It works on Windows and on Ubuntu
Solution 3
import sys
import time
for i in range(10):
print '\r', # print is Ok, and comma is needed.
time.sleep(0.3)
print i,
sys.stdout.flush() # flush is needed.
And if on the IPython-notebook, just like this:
import time
from IPython.display import clear_output
for i in range(10):
time.sleep(0.25)
print(i)
clear_output(wait=True)
Solution 4
I just had this problem. You can still use \r
, even in Windows Command Prompt, however, it only takes you back to the previous linebreak (\n
).
If you do something like this:
cnt = 0
print str(cnt)
while True:
cnt += 1
print "\r" + str(cnt)
You'll get:
0
1
2
3
4
5
...
That's because \r
only goes back to the last line. Since you already wrote a newline character with the last print statement, your cursor goes from the beginning of a new empty line to the beginning of the same new empty line.
To illustrate, after you print the first 0, your cursor would be here:
0
| # <-- Cursor
When you \r
, you go to the beginning of the line. But you're already on the beginning of the line.
The fix is to avoid printing a \n
character, so your cursor is on the same line and \r
overwrites the text properly. You can do that with print 'text',
. The comma prevents the printing of a newline character.
cnt = 0
print str(cnt),
while True:
cnt += 1
print "\r" + str(cnt),
Now it will properly rewrite lines.
Note that this is Python 2.7, hence the print
statements.
Solution 5
Easy method:
import sys
from time import sleep
import os
#print("\033[y coordinate;[x coordinateH Hello")
os.system('cls')
sleep(0.2)
print("\033[1;1H[]")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H []")
sleep(0.2)
print("\033[1;1H[]")
sleep(0.2)
Aaron Digulla
I'm a software developer living in Switzerland. You can reach me at digulla at hepe dot com.
Updated on January 03, 2022Comments
-
Aaron Digulla over 2 years
On Unix, I can either use
\r
(carriage return) or\b
(backspace) to overwrite the current line (print over text already visible) in the shell.Can I achieve the same effect in a Windows command line from a Python script?
I tried the curses module but it doesn't seem to be available on Windows.