【问题标题】:How do I combine TimeoutError and tqdm progress bar in multiprocessing?如何在多处理中结合 TimeoutError 和 tq​​dm 进度条?
【发布时间】:2019-06-05 17:43:08
【问题描述】:

我想同时使用 TimeoutError 和 tq​​dm 进度条执行多处理。

我已经成功地分别尝试了它们。应该如何结合逻辑?

目标:

  • 进度条应该随着每次 imap_unordered 调用而更新

  • 每个进程都应该检查TimeoutError

我已经尝试了一百万种方法来组合它们(未显示)。每次我用 tqdm 包装 imap_unordered 调用时,我都无法访问“res.next”方法进行超时。

from multiprocessing import Pool, TimeoutError
from tqdm import tqdm

def runner(obj):
    obj.go()
    return obj

def dispatch(objs):

    with Pool() as pool:
        newObjs = list(tqdm(pool.imap_unordered(runner, objs), total=len(objs)))

    # need to find a way to integrate TimeoutError into progress bar
    # I've tried this a million ways using multiprocessing

    # try:
    #     res.next(timeout=10)
    # except TimeoutError:
    #     raise

    return newObjs

代码非常适合进度条。需要跟踪任何进程是否超过超时。

【问题讨论】:

    标签: python timeout python-multiprocessing tqdm


    【解决方案1】:

    您可以在没有迭代器的情况下分配进度条并使用update() 手动更新它。

    from multiprocessing import Pool, TimeoutError as mpTimeoutError
    from tqdm import tqdm
    
    
    def runner(obj):
        obj.go()
        return obj
    
    
    def dispatch(objs):
        with Pool() as pool:
            it = pool.imap_unordered(runner, objs)
            pbar = tqdm(total=len(objs))
            new_objs = []
    
            while True:
                try:
                    new_objs.append(it.next(timeout=10))
                    pbar.update()
    
                except mpTimeoutError:
                    raise
    
                except StopIteration:
                    # signal that the iterator is exhausted
                    pbar.close()
                    break
    
        return new_objs
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-31
      • 2018-10-13
      • 2023-04-01
      • 1970-01-01
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多