Python Progress Bar

后端 未结 30 2615
礼貌的吻别
礼貌的吻别 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 07:00

    This answer doesn't rely on external packages, I also think that most people just want a ready-made piece of code. The code below can be adapted to fit your needs by customizing: bar progress symbol '#', bar size, text prefix etc.

    import sys
    
    def progressbar(it, prefix="", size=60, file=sys.stdout):
        count = len(it)
        def show(j):
            x = int(size*j/count)
            file.write("%s[%s%s] %i/%i\r" % (prefix, "#"*x, "."*(size-x), j, count))
            file.flush()        
        show(0)
        for i, item in enumerate(it):
            yield item
            show(i+1)
        file.write("\n")
        file.flush()
    

    Usage:

    import time
    
    for i in progressbar(range(15), "Computing: ", 40):
        time.sleep(0.1) # any calculation you need
    

    Output:

    Computing: [################........................] 4/15
    
    • Doesn't require a second thread. Some solutions/packages above require. A second thread can be a problem, for a jupyter notebook, for example.

    • Works with any iterable it means anything that len() can be used on. A list, a dict of anything for example ['a', 'b', 'c' ... 'g']

    • Works with generators only have to wrap it with a list(). For example for i in progressbar(list(your_generator), "Computing: ", 40):

    You can also change output by changing file to sys.stderr for example

提交回复
热议问题