Search code examples
python-3.xtqdm

resetting tqdm progress bar


I want to reset a tqdm progress bar.

This is my code:

s = tqdm(range(100))
for x in s:
    pass

# Reset it here
s.reset(0)

for x in s:
    pass

Tqdm PB works only for the first loop. I tried to reset it using .reset(0) function but it doesn't work.

The ouput of the above code is:

100%|██████████| 100/100 [00:00<?, ?it/s]

I noticed that they use here: Restting progress bar counter this code

pbar.n = 0
pbar.refresh()

but it doesn't work as well.


Solution

  • When wrapping an iterable, tqdm will close() the bar when the iterable has been exhausted. This means reusing (refresh() etc) won't work. You can solve your problem manually:

    from tqdm import tqdm
    s = range(100)
    t = tqdm(total=len(s))
    for x in s:
        t.update()
    t.refresh()  # force print final state
    
    t.reset()  # reuse bar
    for x in s:
        t.update()
    t.close()  # close the bar permanently