Python Progress Bar

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

    There are specific libraries (like this one here) but maybe something very simple would do:

    import time
    import sys
    
    toolbar_width = 40
    
    # setup toolbar
    sys.stdout.write("[%s]" % (" " * toolbar_width))
    sys.stdout.flush()
    sys.stdout.write("\b" * (toolbar_width+1)) # return to start of line, after '['
    
    for i in xrange(toolbar_width):
        time.sleep(0.1) # do real work here
        # update the bar
        sys.stdout.write("-")
        sys.stdout.flush()
    
    sys.stdout.write("]\n") # this ends the progress bar
    

    Note: progressbar2 is a fork of progressbar which hasn't been maintained in years.

提交回复
热议问题