Add progress bar to a python function

喜你入骨 提交于 2020-07-18 02:09:29

问题


Appreciate any help for a beginner :) I tried the below but not sure how to wrap the def Job():

import time
from progressbar import ProgressBar


pbar = ProgressBar()
def job():
        Script ....
        Script ...
        Script ...
        Script ...

回答1:


You can use the bar object this way:

import time
import progressbar


def job():
    bar = progressbar.ProgressBar()
    for i in bar(range(100)):
        ... # Code that you want to run
        #time.sleep(0.02)

job()

If the code you want to execute has fast execution time, you can put a time.sleep() inside in order not to have progressbar set to 100% in the beginning.




回答2:


You can use progressbar like this:

import time
from progressbar import ProgressBar

pbar = ProgressBar()

def job():
    for i in pbar(xrange(5)):
        print(i)

job()

Output looks like this:

0 0% |                                                                         |
120% |##############                                                           |
240% |#############################                                            |
360% |###########################################                              |
480% |##########################################################               |
100% |#########################################################################

I like tqdm a lot more and it works the same way.

from tqdm import tqdm
for i in tqdm(range(10000)):
    pass

Image




回答3:


From the documentation, it seems really straight forward

pbar = ProgressBar().start()
def job():
   total_steps = 7
    # script 1
    pbar.update((1/7)*100)  # current step/total steps * 100
    # script 2
    pbar.update((2/7)*100)  # current step/total steps * 100
    # ....
    pbar.finish()

Also, don't be afraid to check out the source code https://github.com/niltonvolpato/python-progressbar/blob/master/progressbar/progressbar.py



来源:https://stackoverflow.com/questions/48573445/add-progress-bar-to-a-python-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!