如何在多处理中结合TimeoutError和tqdm进度条?

2024-04-20 10:51:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用TimeoutError和tqdm进度条执行多处理。你知道吗

我成功地分别尝试了它们。我应该如何组合逻辑?你知道吗

目标:

  • 进度条应该随着每次imap\U无序调用而更新

  • 应检查每个进程是否存在超时错误

我尝试了无数种方法来组合它们(未显示)。每次我用tqdm包装imap\u无序调用时,我都无法访问“下一个解决方案“超时的方法。你知道吗

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

代码非常适用于进度条。需要跟踪任何进程是否超过超时。你知道吗


Tags: 方法进度条fromimportobj进程defmultiprocessing
1条回答
网友
1楼 · 发布于 2024-04-20 10:51:05

您可以在不使用迭代器的情况下分配进度条,并使用^{}手动更新它。你知道吗

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

相关问题 更多 >