Search code examples
pythontqdm

tqdm with intervals inside larger loop


I have an outer loop

for i in itertools.count():

and there are events that occur at intervals:

if i % log_interval == 0:
    perform_logging()
if i % save_interval == 0:
    save()
# etc.

I would like to use tqdm to track the progress toward the next log/save/etc. Ideally, tqdm would print several progress bars simultaneously, a la

enter image description here

What's the best way to do this? Thanks!


Solution

  • Something like this:

    from __future__ import division, print_function
    import itertools
    from math import ceil
    from tqdm import tqdm
    from time import sleep
    
    total = 987
    log_interval = 2
    save_interval = 9
    with tqdm(total=total, desc="overall") as tOverall:
      with tqdm(total=ceil(total / log_interval), unit="log") as tLog:
        with tqdm(total=ceil(total / save_interval), unit="save") as tSave:
          for i in itertools.count(0, 1):
            sleep(0.01)
            if i % log_interval == 0:
              perform_logging()
              tLog.update()
            if i % save_interval == 0:
              save()
              tSave.update()
            if i + 1 == total:
              break
            tOverall.update()
    print('\n')