Search code examples
pythonprogress-bar

Double Progress Bar in Python


Is there a way to create a double progress bar in Python? I want to run two loops inside each other. For each loop I want to have a progress bar. My program looks like:

import time
for i1 in range(5):
    for i2 in range(300):
        # do something, e.g. sleep
        time.sleep(0.01)
        # update upper progress bar
    # update lower progress bar

The output somewhere in the middle should look something like

50%|############################                                  |ETA: 0:00:02
80%|##################################################            |ETA: 0:00:04

The already existing really cool progressbar module doesn't seem to support that.


Solution

  • Use the nested progress bars feature of tqdm, an extremely low overhead, very customisable progress bar library:

    $ pip install -U tqdm
    

    Then:

    from tqdm import tqdm
    # from tqdm.auto import tqdm  # notebook compatible
    import time
    for i1 in tqdm(range(5)):
        for i2 in tqdm(range(300), leave=False):
            # do something, e.g. sleep
            time.sleep(0.01)
    

    (The leave=False is optional - needed to discard the nested bars upon completion.)

    You can also use from tqdm import trange and then replace tqdm(range(...)) with trange(...). You can also get it working in a notebook.

    Alternatively if you want just one bar to monitor everything, you can use tqdm's version of itertools.product:

    from tqdm.contrib import itertools
    import time
    for i1, i2 in itertools.product(range(5), range(300)):
        # do something, e.g. sleep
        time.sleep(0.01)