Python Progress Bar

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

    It is quite straightforward in Python3:

       import time
       import math
    
        def show_progress_bar(bar_length, completed, total):
            bar_length_unit_value = (total / bar_length)
            completed_bar_part = math.ceil(completed / bar_length_unit_value)
            progress = "*" * completed_bar_part
            remaining = " " * (bar_length - completed_bar_part)
            percent_done = "%.2f" % ((completed / total) * 100)
            print(f'[{progress}{remaining}] {percent_done}%', end='\r')
    
        bar_length = 30
        total = 100
        for i in range(0, total + 1):
            show_progress_bar(bar_length, i, total)
            time.sleep(0.1)
    
        print('\n')
    

提交回复
热议问题