将自定义变量/统计信息添加到 tqdm 栏

ang*_*gel 5 python python-3.x tqdm

我想知道是否可以将自定义变量添加到 tqdm 栏,其中该值有时会随着每次迭代而更新。例如:

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

我想exception_countbar_format参数的某处添加变量作为自定义错误计数器的类型。

Dhi*_*dhi 2

可以按照tqdm 的 github 存储库中记录的以下方式执行此操作

pbar = tqdm(["a", "b", "c", "d"])
   for char in pbar:
      sleep(0.25)
      pbar.set_description("Processing %s" % char)
Run Code Online (Sandbox Code Playgroud)

这将动态更新每次迭代的进度条描述。

对于您的问题,您需要执行以下操作:

exception_count = 0

pbar = tqdm(1000)
for _ in pbar:
    try:
       do_stuff()
       pbar.set_description(f"Exceptions: counthere | Elapsed: {elapsed} |{rate_fmt}")
    except Exception:
       exception_count += 1
Run Code Online (Sandbox Code Playgroud)