Python Progress Bar

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

    To use any progress-bar frameworks in a useful manner, to get an actual progress percent and an estimated ETA, you need to be able to declare how many steps it will have.

    So, your compute function in another thread, are you able to split it in a number of logical steps? Can you modify its code?

    You don't need to refactor or split it in any way, you could just put some strategic yields in some places or if it has a for loop, just one!

    That way, your function will look something like this:

    def compute():
        for i in range(1000):
            time.sleep(.1)  # process items
            yield  # insert this and you're done!
    

    Then just install:

    pip install alive-progress
    

    And use it like:

    from alive_progress import alive_bar
    
    with alive_bar(1000) as bar:
        for i in compute():
            bar()
    

    To get a cool progress-bar!

    |█████████████▎                      | ▅▃▁ 321/1000 [32%] in 8s (40.1/s, eta: 16s)
    

    Disclaimer: I'm the author of alive-progress, but it should solve your problem nicely. Read the documentation at https://github.com/rsalmei/alive-progress, here is an example of what it can do:

    alive-progress

提交回复
热议问题