pythonで実現したもう一つのコンサート下のプログレスバー


Consolie(text)progress indicator class
ソースアドレス:http://snipperize.todayclose.com/snippet/py/Console-%28text%29-progress-inndicator-class-1-4253/

  
  
  
  
  1. class progressbarClass:  
  2.     def __init__(self, finalcount, progresschar=None): 
  3.         import sys 
  4.         self.finalcount=finalcount 
  5.         self.blockcount=0 
  6.         # 
  7.         # See if caller passed me a character to use on the 
  8.         # progress bar (like "*").  If not use the block 
  9.         # character that makes it look like a real progress 
  10.         # bar. 
  11.         # 
  12.         if not progresschar: self.block=chr(178
  13.         else:                self.block=progresschar 
  14.         # 
  15.         # Get pointer to sys.stdout so I can use the write/flush 
  16.         # methods to display the progress bar. 
  17.         # 
  18.         self.f=sys.stdout 
  19.         # 
  20.         # If the final count is zero, don't start the progress gauge 
  21.         # 
  22.         if not self.finalcount : return 
  23.         self.f.write('
    ------------------ % Progress -------------------1
    '
  24.         self.f.write('    1    2    3    4    5    6    7    8    9    0
    '
  25.         self.f.write('----0----0----0----0----0----0----0----0----0----0
    '
  26.         return 
  27.  
  28.     def progress(self, count): 
  29.         # 
  30.         # Make sure I don't try to go off the end (e.g. >100%) 
  31.         # 
  32.         count=min(count, self.finalcount) 
  33.         # 
  34.         # If finalcount is zero, I'm done 
  35.         # 
  36.         if self.finalcount: 
  37.             percentcomplete=int(round(100*count/self.finalcount)) 
  38.             if percentcomplete < 1: percentcomplete=1 
  39.         else
  40.             percentcomplete=100 
  41.              
  42.         #print "percentcomplete=",percentcomplete 
  43.         blockcount=int(percentcomplete/2
  44.         #print "blockcount=",blockcount 
  45.         if blockcount > self.blockcount: 
  46.             for i in range(self.blockcount,blockcount): 
  47.                 self.f.write(self.block) 
  48.                 self.f.flush() 
  49.                  
  50.         if percentcomplete == 100self.f.write("
    "
  51.         self.blockcount=blockcount 
  52.         return 
  53.      
  54. if __name__ == "__main__"
  55.     from time import sleep 
  56.     pb=progressbarClass(8,"*"
  57.     count=0 
  58.     while count<9
  59.         count+=1 
  60.         pb.progress(count) 
  61.         sleep(0.2
  62.  
  63.     pb=progressbarClass(100
  64.     pb.progress(20
  65.     sleep(0.2
  66.     pb.progress(47
  67.     sleep(0.2
  68.     pb.progress(90
  69.     sleep(0.2
  70.     pb.progress(100
  71.     print "testing 1:" 
  72.     pb=progressbarClass(1
  73.     pb.progress(1