How to reset cursor to the beginning of the same line in Python
Solution 1:
import sys, time
for i in xrange(0, 101, 10):
print '\r>> You have finished %d%%' % i,
sys.stdout.flush()
time.sleep(2)
print
The \r
is the carriage return. You need the comma at the end of the print
statement to avoid automatic newline. Finally sys.stdout.flush()
is needed to flush the buffer out to stdout.
For Python 3, you can use:
print("\r>> You have finished {}%".format(i), end='')
Solution 2:
Python 3
You can use keyword arguments to print
:
print('string', end='\r', flush=True)
-
end='\r'
replaces the default end-of-line behavior with'\r'
-
flush=True
flushes the buffer, making the printed text appear immediately.
Python 2
In 2.6+ you can use from __future__ import print_function
at the start of the script to enable Python 3 behavior. Or use the old way:
Python's print
puts a newline after each command, unless you suppress it with a trailing comma. So, the print command is:
print 'You have finished {0}%\r'.format(percentage),
Note the comma at the end.
Unfortunately, Python only sends the output to the terminal after a complete line. The above is not a complete line, so you need to flush
it manually:
import sys
sys.stdout.flush()
Solution 3:
On linux( and probably on windows) you can use curses module like this
import time
import curses
win = curses.initscr()
for i in range(100):
win.clear()
win.addstr("You have finished %d%%"%i)
win.refresh()
time.sleep(.1)
curses.endwin()
Benfit with curses as apposed to other simpler technique is that, you can draw on terminal like a graphics program, because curses provides moving to any x,y position e.g. below is a simple script which updates four views
import time
import curses
curses.initscr()
rows = 10
cols= 30
winlist = []
for r in range(2):
for c in range(2):
win = curses.newwin(rows, cols, r*rows, c*cols)
win.clear()
win.border()
winlist.append(win)
for i in range(100):
for win in winlist:
win.addstr(5,5,"You have finished - %d%%"%i)
win.refresh()
time.sleep(.05)
curses.endwin()