将 tqdm 与多处理结合使用

rou*_*rld 5 python multiprocessing tqdm

我在 Python 3.7 中使用多处理来启动几个长时间运行的操作。每个单独的过程都需要几分钟才能完成。我想要同时显示正在运行的每个单独进程的进度条。我一直无法让它工作,因为进度条在我当前徒劳的尝试中不断跳跃并相互替换。

我这样创建我的流程:

with Pool(processes=cpu_count()) as pool:
    return pool.starmap(_execute_long_running_process, items)
Run Code Online (Sandbox Code Playgroud)

_execute_long_running_process我的函数内部有一个for循环,我希望进度条跟踪它。

for i in tqdm(list_of_things_to_process, leave=False):
    # do a thing
Run Code Online (Sandbox Code Playgroud)

我相信我的问题是由于每个tqdm进度条存在于与主流程分开的自己的流程中而产生的。我不确定有什么解决方法可以使它们按照我的预期运行,其中有几个进度条正在更新。

J_H*_*J_H 4

我通过以下方式构建计算获得了良好的结果:

    with multiprocessing.Pool() as p:
        list(tqdm.tqdm(p.imap_unordered(inserter, tasks), total=len(tasks)))
Run Code Online (Sandbox Code Playgroud)

这为您提供了所有任务的单一、统一的进度条。