Reputation: 1982
To hide the tqdm
progress bar after running a computation I pass leave=False
, as in the following example code:
from tqdm import tqdm
from time import sleep
text = ""
for char in tqdm(["a", "b", "c", "d"], desc="Loop", leave=True):
sleep(0.25)
text = text + char
However, I would like to keep the iteration statistics when the loop is done (hiding the bar), for example:
Loop: 4 [00:01, 3.99it/s]
for total number of iterations, total time taken and iterations per second. Is there a way to do this?
I tried doing
class tqdm_f(tqdm):
def __init__(self, *args, **kwargs):
self.done_fmt = kwargs.pop("done_fmt",
"{desc}: {total_fmt} [{elapsed}, {rate_fmt}{postfix}]")
super().__init__(*args, **kwargs)
def update_to(self, b=1, bsize=1, tsize=None):
if b * bsize == self.total:
self.bar_format = self.done_fmt
self.update(b * bsize - self.n) # will also set self.n = b * bsize
and using my tqdm_f
instead but that did not work for some reason.
Upvotes: 0
Views: 3845
Reputation: 81
You can set the ncols
of tqdm to zero in the last iteration:
from tqdm import tqdm
from time import sleep
text = ""
progress_bar = tqdm(["a", "b", "c", "d"], desc="Loop")
for char in progress_bar:
sleep(0.25)
text = text + char
if char == "d":
progress_bar.ncols=0
According to the documentation, setting ncols
to zero will cause the bar to disappear. To do so only in the last iteration will keep the bar in all previous iterations. There's no need to use the leave
argument.
Alternative: If you want to remove the bar altogether, you can set ncols
to zero right from the start:
from tqdm import tqdm
from time import sleep
text = ""
for char in tqdm(["a", "b", "c", "d"], desc="Loop", ncols=0):
sleep(0.25)
text = text + char
Upvotes: 1