如何在多处理中结合使用TimeoutError和tqdm进度栏?

时间:2019-06-05 17:43:08

标签: python timeout python-multiprocessing tqdm

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

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

目标:

  • 进度栏应随每个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

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

1 个答案:

答案 0 :(得分:0)

您可以分配没有迭代器的进度条,并使用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