performance - fixing a Python progress bar in Command Prompt -


i have wrote following code (reviewed in code review) in order print progress bar in python 2.7 (ps: know there progressbar module in python)

from __future__ import division import sys  class progress(object):     def __init__(self, maxval):         self._pct = 0         self.maxval = maxval      def update(self, value):         pct = int((value / self.maxval) * 100.0)         if self._pct != pct:             self._pct = pct             self.display()      def start(self):         self.update(0)      def finish(self):         self.update(self.maxval)      def display(self):         sys.stdout.write("|%-100s| %d%%" % ('#' *self._pct, self._pct) + '\n')         sys.stdout.flush()  # test import time  toolbar_width = 300 pbar = progress(toolbar_width) pbar.start() in xrange(toolbar_width):     time.sleep(0.1) # real work here     pbar.update(i) pbar.finish() 

i wish use progress bar in ide (ex: pyscripet, pycharm , etc) , command prompt. when run command prompt have following 2 problem cannot understand how can fix.

enter image description here

  1. first, progress bar prints out limit (i used 100s)
  2. second, progressbar print bar 1 after other. wish have 1 bar increase during loop

1. may wrapping due line length, terminal looks narrower 100 characters wide. if want assume 80 characters (what consoles default to), think you've got 7 characters of other stuff, use width of 73 characters progress bar.

    sys.stdout.write("|%-73s| %3d%%" % ('#' * int(self._pct*.73), self._pct) + '\n') 

2. stay on same line, use sys.stdout.write , don't include newline @ end. add \r beginning of each line return beginning.

        sys.stdout.write("\r|%-73s| %3d%%" % ('#' * int(self._pct*.73), self._pct)) 

you can use %3d%% pad percentage, stays right aligned consistently.


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -