How to simulate a run counter in a command line application in Python?

My Python program performs a series of operations and displays some diagnostic data. I would also like to have a progress counter as follows:

Percentage done: 25%

where the number increases "in place". If I use only string operators, I can write single numbers, but it clutters the screen. Is there a way to achieve this, for example, using some escape char for backspace to clear the number and write the next one?

thank

+5
source share
5 answers

Here is an example of showing the percentage reading of a file:

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)
+7
source

Poor decision:

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

- . ( "\ r" ) , . "," print, .

, . , .

+4
+2

Progress Bar, , CLI ( ).

 class ProgressBar(object):
     def __init__(self, total=100, stream=sys.stderr):
         self.total = total
         self.stream = stream
         self.last_len = 0
         self.curr = 0

     def count(self):
         self.curr += 1
         self.print_progress(self.curr)

     def print_progress(self, value):
         self.stream.write('\b' * self.last_len)
         pct = 100 * self.curr / self.total
         out = '{:.2f}% [{}/{}]'.format(pct, self.curr, self.total)
         self.last_len = len(out)
         self.stream.write(out)
         self.stream.flush()

eg.

>>> p = ProgressBar(1000)
>>> p.print_progress(500)
50% [500/1000]
0
source

All Articles