Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to replace tqdm progress bar by next one in nested loop?

I use tqdm module in Jupyter Notebook. And let's say I have the following piece of code with a nested for loop.

import time
from tqdm.notebook import tqdm

for i in tqdm(range(3)):
    for j in tqdm(range(5)):
        time.sleep(1)

The output looks like this:

100%|██████████| 3/3 [00:15<00:00, 5.07s/it]
100%|██████████| 5/5 [00:10<00:00, 2.02s/it]

100%|██████████| 5/5 [00:05<00:00, 1.01s/it]

100%|██████████| 5/5 [00:05<00:00, 1.01s/it]

Is there any option, how to show only current j progress bar during the run? So, the final output after finishing the iteration would look like this?

100%|██████████| 3/3 [00:15<00:00, 5.07s/it]
100%|██████████| 5/5 [00:05<00:00, 1.01s/it]
like image 287
Jaroslav Bezděk Avatar asked Mar 30 '20 10:03

Jaroslav Bezděk


2 Answers

You can use leave param when create progress bar. Something like this:

import time
from tqdm import tqdm

for i in tqdm(range(3)):
    for j in tqdm(range(5), leave=bool(i == 2)):
        time.sleep(1)
like image 106
Anton Pomieshchenko Avatar answered Oct 02 '22 11:10

Anton Pomieshchenko


You can achieve this by resetting the progress bar object every time before inner loop starts.

Try the following code to achieve the results you want.

import time
from tqdm.notebook import tqdm

#initializing progress bar objects
outer_loop=tqdm(range(3))
inner_loop=tqdm(range(5))

for i in range(len(outer_loop)):
    inner_loop.refresh()  #force print final state
    inner_loop.reset()  #reuse bar
    outer_loop.update() #update outer tqdm

    for j in range(len(inner_loop)):
        inner_loop.update() #update inner tqdm
        time.sleep(1)

Output:

Output

like image 34
Hamza Khurshid Avatar answered Oct 02 '22 09:10

Hamza Khurshid