简体   繁体   English

将进度条添加到python函数

[英]Add progress bar to a python function

Appreciate any help for a beginner :) I tried the below but not sure how to wrap the def Job() : 感谢初学者的帮助:)我尝试了以下方法,但不确定如何包装def Job()

import time
from progressbar import ProgressBar


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

You can use progressbar like this: 您可以这样使用progressbar条:

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. 我更喜欢tqdm ,它的工作方式相同。

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

Image 图片

在此处输入图片说明

You can use the bar object this way: 您可以通过以下方式使用bar对象:

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. 如果要执行的代码执行时间较快,则可以在其中放入time.sleep() ,以免开始时将进度条设置为100%。

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://github.com/niltonvolpato/python-progressbar/blob/master/progressbar/progressbar.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM