Python Progress Bar

后端 未结 30 2260
礼貌的吻别
礼貌的吻别 2020-11-22 06:13

How do I use a progress bar when my script is doing some task that is likely to take time?

For example, a function which takes some time to complete and returns

30条回答
  •  失恋的感觉
    2020-11-22 06:58

    Use the progress library!

    pip install progress
    

    Here is a custom subclass I wrote to format the ETA/Elapsed times into a better readable format:

    import datetime
    from progress.bar import IncrementalBar
    
    
    class ProgressBar(IncrementalBar):
        '''
        My custom progress bar that:
           - Show %, count, elapsed, eta
           - Time is shown in H:M:S format
        '''
    
        message = 'Progress'
        suffix  = '%(percent).1f%% (%(index)d/%(max)d) -- %(elapsed_min)s (eta: %(eta_min)s)'
    
        def formatTime(self, seconds):
            return str(datetime.timedelta(seconds=seconds))
    
        @property
        def elapsed_min(self):
            return self.formatTime(self.elapsed)
    
        @property
        def eta_min(self):
            return self.formatTime(self.eta)
    
    if __name__=='__main__':
        counter = 120
        bar     = ProgressBar('Processing', max=counter)
    
        for i in range(counter):
            bar.next()
            time.sleep(1)
    
        bar.finish()
    

提交回复
热议问题