python - 如何在多处理中结合 TimeoutError 和 tq​​dm 进度条?

标签 python timeout python-multiprocessing tqdm

我想使用 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

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

最佳答案

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

关于python - 如何在多处理中结合 TimeoutError 和 tq​​dm 进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56465522/

相关文章:

c# - Selenium C#超时异常

node.js - 定期检查和清理服务器中的文件

python - 使用 Python 多处理/线程解决数据不一致问题

python - 在不复制的情况下在多个进程之间共享非常大的字典的最快方法

python - Gunicorn 多处理中的原子代码/仅在工作程序 1 中运行代码?

python - Celery 任务立即自动发现

Python Flask "send_file()"方法类型错误

python - 递归限制给出阶乘函数的错误

python - Tensorflow string_input_ Producer 卡在队列中

c# - 为什么 HttpWebRequest ReadWriteTimeout 设置为 5 分钟?