If I had the following code:
for x in range(10):
print x
I would get the output of
1
2
etc..
What I
Better to overwrite the whole line otherwise the new line will mix with the old ones if the new line is shorter.
import time, os
for s in ['overwrite!', 'the!', 'whole!', 'line!']:
print(s.ljust(os.get_terminal_size().columns - 1), end="\r")
time.sleep(1)
Had to use columns - 1
on Windows.
@Mike DeSimone answer will probably work most of the time. But...
for x in ['abc', 1]:
print '{}\r'.format(x),
-> 1bc
This is because the '\r'
only goes back to the beginning of the line but doesn't clear the output.
If POSIX support is enough for you, the following would clear the current line and leave the cursor at its beginning:
print '\x1b[2K\r',
It uses ANSI escape code to clear the terminal line. More info can be found in wikipedia and in this great talk.
The (not so good) solution I've found looks like this:
last_x = ''
for x in ['abc', 1]:
print ' ' * len(str(last_x)) + '\r',
print '{}\r'.format(x),
last_x = x
-> 1
One advantage is that it will work on windows too.
I had the same question before visiting this thread. For me the sys.stdout.write worked only if I properly flush the buffer i.e.
for x in range(10):
sys.stdout.write('\r'+str(x))
sys.stdout.flush()
Without flushing, the result is printed only at the end out the script
I couldn't get any of the solutions on this page to work for IPython, but a slight variation on @Mike-Desimone's solution did the job: instead of terminating the line with the carriage return, start the line with the carriage return:
for x in range(10):
print '\r{0}'.format(x),
Additionally, this approach doesn't require the second print statement.
Since I ended up here via Google but am using Python 3, here's how this would work in Python 3:
for x in range(10):
print("Progress {:2.1%}".format(x / 10), end="\r")
Related answer here: How can I suppress the newline after a print statement?
I'm a bit surprised nobody is using the backspace character. Here's one that uses it.
import sys
import time
secs = 1000
while True:
time.sleep(1) #wait for a full second to pass before assigning a second
secs += 1 #acknowledge a second has passed
sys.stdout.write(str(secs))
for i in range(len(str(secs))):
sys.stdout.write('\b')