views:

127

answers:

5

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

A: 

you could try looking at this library, which basically does everything for you:

http://code.activestate.com/recipes/473899-progress-meter/

lugte098
A: 

Look at he answers here.

miles82
since it's an exact duplicate, your answer should be a comment
SilentGhost
+3  A: 

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)
zoli2k
+2  A: 

Poor mans solution:

  import time
  for i in range(10):
    print "\r", i,
    time.sleep(1)

The trick is the print statement. "\r" sets the cursor back to the first column (carriage returen) on the same line, without starting a new line. The trailing colon "," tells print not to prooduce a newline either.

Depending on your output, you may want to pad the print statement with trailing spacess to ensure that fragments from longer previous lines do not interfer with your current print statement. Its probably best to assemble a string which has fixed length for any progress information.

Bernd
zoli2k is right. You shoud call stdout.flush() in order to get a realtime reading.
Bernd
+1  A: 

Have a look at Animated Terminal Progress Bar in Python by Nadia Alramli

Michał Niklas