Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I simulate a progress counter in a command line application in Python?

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

like image 654
CRP Avatar asked Apr 22 '10 08:04

CRP


2 Answers

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)
like image 188
zoli2k Avatar answered Nov 19 '22 04:11

zoli2k


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)
like image 22
Bernd Avatar answered Nov 19 '22 05:11

Bernd