My Python program does a series of things and prints some diagnostic output. I would also like to have a progress counter like this:
Percentage done: 25%
where the number increases "in place". If I use only string statements I can write separate numbers, but that would clutter the screen. Is there some way to achieve this, for example using some escape char for backspace in order to clear a number and write the next one?
Thanks
Here is an example for showing file read percentage:
from sys import *
import os
import time
Size=os.stat(argv[1])[6] #file size
f=open(argv[1],"r");
READED_BYTES=0
for line in open(argv[1]): #Read every line from the file
READED_BYTES+=len(line)
done=str(int((float(READED_BYTES)/Size)*100))
stdout.write(" File read percentage: %s%% %s"%(done,"\r"))
stdout.flush();
time.sleep(1)
Poor man's solution:
import time
for i in range(10):
print "\r", i,
time.sleep(1)
The trick is the print statement. The carriage return ("\r") sets the cursor back to the first column on the same line, without starting a new line. The trailing comma "," tells print not to produce a newline either.
Depending on your output, you may want to pad the print statement with trailing spaces to ensure that fragments from longer previous lines do not interfere with your current print statement. Its probably best to assemble a string which has fixed length for any progress information.
Updating answer for Python 3+:
import time
for i in range(10):
print('\r', str(i), end = '')
time.sleep(1)
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