Python進捗バーの表示

4807 ワード

How to show process bar in python
Sometimes when we deal with some time-consuming tasks, we need to show the process bar, there are many ways to do this, the best way is to use the model tqdm;
  • use tqdm
  • pip install tqdm
    from tqdm import *
    
    for i in tqdm(range(n)):
        print i
  • use self-create class
  • save following code as process.py

  • # -*- coding: UTF-8 -*-
    
    import sys, time
    
    class ShowProcess():
        """
                
                           
        """
        i = 0 #        
        max_steps = 0 #          
        max_arrow = 50 #      
        infoDone = 'done'
    
        #      ,           
        def __init__(self, max_steps, infoDone = 'Done'):
            self.max_steps = max_steps
            self.i = 0
            self.infoDone = infoDone
    
        #     ,         i    
        #    [>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>]100.00%
        def show_process(self, i=None):
            if i is not None:
                self.i = i
            else:
                self.i += 1
            num_arrow = int(self.i * self.max_arrow / self.max_steps) #       '>'
            num_line = self.max_arrow - num_arrow #       '-'
            percent = self.i * 100.0 / self.max_steps #      ,   xx.xx%
            process_bar = '[' + '>' * num_arrow + '-' * num_line + ']'\
                          + '%.2f' % percent + '%' + '\r' #       ,'\r'          
            sys.stdout.write(process_bar) #          
            sys.stdout.flush()
            if self.i >= self.max_steps:
                self.close()
    
        def close(self):
            print('')
            print(self.infoDone)
            self.i = 0
    
    if __name__=='__main__':
        max_steps = 100
    
        process_bar = ShowProcess(max_steps, 'OK')
    
        for i in range(max_steps):
            process_bar.show_process()
            time.sleep(0.01)
  • if you need to use it, just
  • from process import ShowProcess
        max_steps = 100
        process_bar = ShowProcess(max_steps, 'OK')
        for i in range(max_steps):
            process_bar.show_process()
            time.sleep(0.01)