【问题标题】:Adding custom variable/stats to tqdm bar将自定义变量/统计信息添加到 tqdm 条
【发布时间】:2019-03-20 18:03:11
【问题描述】:

我想知道是否可以将自定义变量添加到 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

我想在bar_format 参数中的某处添加exception_count 变量作为一种自定义错误计数器。

【问题讨论】:

    标签: python python-3.x tqdm


    【解决方案1】:

    您可以使用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()
    

    【讨论】:

      【解决方案2】:

      可以按照github repository of tqdm 中所述的以下方式执行此操作

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

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

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

      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
      

      【讨论】:

        猜你喜欢
        • 2021-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多