11 October, 2015

Python Progress Bar

Was recently writing some python to process some test cases.  One long'ish testcase would benefit from a progress bar, slapped one together below.

One thing to note, progress doesn't allow going backwards, but indicates in ASCII text the current progress by writing characters and a series of backspaces.



#!/usr/bin/python
import time
import sys
 
class ProgressBar():
  barLen_=0;
  progress_=0;
  def __init__(self,N=10):
    self.barLen_=N;
    print '['+' '*self.barLen_+']',
    print '\b'*(self.barLen_+2),
  def setProgress(self,x):
    sys.stdout.flush();
    k=int(x/100.0*self.barLen_);
    if (k > self.progress_):
      update='\b'+'.'*(k-self.progress_);
      print update,
      self.progress_=k;

N=50
p=ProgressBar(N);

for i in range(0,101):
  p.setProgress(i);
  time.sleep(.05);

The result is of the form:

user@river:~$ ./pBar 
[..............                                  ] 
Enjoy.

2 comments:

Anonymous said...

Hi! I've been reading your blog for a while now and finally got
the courage to go ahead and give you a shout out
from Porter Tx! Just wanted to tell you keep up the fantastic work!

Anonymous said...

Keep this going please, great job!