开发者

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

开发者 https://www.devze.com 2022-12-27 23:26 出处:网络
My Python program does a series of things and prints some diagnostic output. I would also like to have a progress counter like this:

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 don开发者_JAVA百科e: 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)


Here's a really simple Progress Bar class that encapsulates most of what you'd want to do with a CLI progress bar (without the bar).

 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()

E.g.

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

精彩评论

暂无评论...
验证码 换一张
取 消