Mike
Mike

Reputation: 53

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():

import time
from progressbar import ProgressBar


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

Upvotes: 5

Views: 30836

Answers (3)

SomeGuyOnAComputer
SomeGuyOnAComputer

Reputation: 6208

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

enter image description here

Upvotes: 8

Razmooo
Razmooo

Reputation: 506

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.

Upvotes: 3

Arun Karunagath
Arun Karunagath

Reputation: 1578

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

Upvotes: 2

Related Questions