pythontqdm

Progress bar with multiple stats printed in new lines


import numpy as np
from tqdm import tqdm
import time

tot_steps = 100

pbar = tqdm(total=tot_steps)

for i in range(tot_steps):
  time.sleep(0.1)
  x, y, z, k = np.random.rand(4)
  pbar.update(1)
  pbar.set_description(
      f"error[{x:.3f}] _ "
      f"samples[{y:.3f}] _ "
      f"min[{z:.3f}] _ "
      f"max[{k:.3f}] _ "
  )

Output

error[0.145] _ samples[0.255] _ min[0.286] _ max[0.878] _ : 100%|████████████████████| 100/100 [00:13<00:00, 70.96it/s]

But I would like to have something like this

100%|████████████████████| 100/100 [00:13<00:00, 70.96it/s]
error[0.145]
samples[0.255]
min[0.286]
max[0.878]

With the numbers progressively updated without printing everything everytime.

That is, I would like to print the logged stats on new lines. However, if I add \n to the print of the progress bar, it doesn't work (it keeps printing new lines).

EDIT I have accepted nischal's answer, but there is also another way to do that by making the progress bar wrap around multiple lines if needed. I just copy-pasted this code and it works. It is faster than nischal's answer but I can't really control how many lines are used (it depends on the screen width).


Solution

  • You are using set_discription which is embedding stats in the progress bar and it is also overwriting the stats inline instead of updating them. You can try using this snippet instead

    pbar = tqdm(total=tot_steps, position=0)
    for line in [f"error[0.000]", f"samples[0.000]", f"min[0.000]", f"max[0.000]"]:
        tqdm.write(line)
    
    for i in range(tot_steps):
        time.sleep(0.1)
        x, y, z, k = np.random.rand(4)
        print("\033[4A", end="")
        for line in [f"error[{x:.3f}]", f"samples[{y:.3f}]", f"min[{z:.3f}]", f"max[{k:.3f}]"]:
            tqdm.write(line)
        pbar.update(1)
    
    pbar.close()