Python Progress Bar

后端 未结 30 2619
礼貌的吻别
礼貌的吻别 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:57

    Guess i'm a little late but this should work for people working with the current versions of python 3, since this uses "f-strings", as introduced in Python 3.6 PEP 498:

    Code

    from numpy import interp
    
    class Progress:
        def __init__(self, value, end, title='Downloading',buffer=20):
            self.title = title
            #when calling in a for loop it doesn't include the last number
            self.end = end -1
            self.buffer = buffer
            self.value = value
            self.progress()
    
        def progress(self):
            maped = int(interp(self.value, [0, self.end], [0, self.buffer]))
            print(f'{self.title}: [{"#"*maped}{"-"*(self.buffer - maped)}]{self.value}/{self.end} {((self.value/self.end)*100):.2f}%', end='\r')
    

    Example

    #some loop that does perfroms a task
    for x in range(21)  #set to 21 to include until 20
        Progress(x, 21)
    

    Output

    Downloading: [########------------] 8/20 40.00%
    

提交回复
热议问题