Reputation: 10083
Is there a way to create things like progress bars or updating percentages to the command line in python? It would be much preferred to a new line for every update.
something that looks like this
for n in range(10):
print n*10,'%'
Upvotes: 2
Views: 6167
Reputation: 863
Printing the \r
character (carriage return) will move the cursor to the beginning of the line then you can re-write it from there. You will also need to keep the print
function from adding a line break by providing end=''
as a parameter.
To clarify how to use it, the example below increments a progress counter every second, re-writing the line every second:
import time
a = 0
while 1:
text = "progress: " + str(a) + "%"
print ("\r" + text + " ", end='')
time.sleep (1)
a = a + 1
You will need this little amount of empty spaces at the end of the string (after text
in the example). When you print variable-length text (like filenames or paths) you may have a situation where the next line update will be shorter than the previous, and you will need to clean up the excess characters from the previous iteration.
Upvotes: 1