Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom variable/stats to tqdm bar

I am wondering if it possible to add a custom variable to the tqdm bar where the value sometimes updates with each iteration. For example:

exception_count = 0
for _ in tqdm(range(1000), bar_format="Exceptions: counthere | Elapsed: {elapsed} |{rate_fmt}"):
    try:
        do_stuff()
    except Exception:
        exception_count += 1

I would like to add the exception_count variable somewhere in the bar_format parameter as a type of custom error counter.

like image 380
angel Avatar asked Nov 17 '22 13:11

angel


1 Answers

You can add additional stats to the progress bar using postfix.

import random
import time

from tqdm import tqdm


def do_stuff():
    time.sleep(0.01)
    if random.randint(0, 10) < 3:
        raise Exception()


exception_count = 0
with tqdm(
    bar_format="Exceptions: {postfix} | Elapsed: {elapsed} | {rate_fmt}",
    postfix=exception_count,
) as t:
    for _ in range(1000):
        try:
            do_stuff()
        except Exception:
            exception_count += 1
            t.postfix = exception_count
            t.update()
like image 177
pypae Avatar answered Dec 31 '22 13:12

pypae