You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否存在类似tqdm的简便方式实现Python多进程for循环?

满足需求的Python多进程循环库推荐

推荐几个能实现你想要的简洁多进程循环的方案:

1. 用p_tqdm库(最贴合你的预期)

这个库专门把tqdm进度条和多进程结合,语法和你给出的示例几乎一模一样,用起来非常省心。

  • 先安装:pip install p-tqdm
  • 示例代码:
from p_tqdm import p_imap

def some_func(i):
    # 这里写你的业务逻辑
    print(f"处理{i}")

# 完全符合你想要的写法,指定进程数即可
for i in p_imap(some_func, range(100), num_cpus=4):
    # 如果some_func有返回值,这里的i就是返回结果;不需要的话可以直接pass
    pass

如果需要批量处理并收集结果,还可以用p_map,用法类似:

from p_tqdm import p_map

results = p_map(some_func, range(100), num_cpus=4)
# results里是所有some_func的返回值列表

2. 标准库+tqdm(无需额外装库)

如果不想新增依赖,用Python标准库的concurrent.futures结合tqdm也能实现类似效果:

from concurrent.futures import ProcessPoolExecutor
from tqdm import tqdm

def some_func(i):
    # 业务逻辑
    pass

with ProcessPoolExecutor(max_workers=4) as executor:
    # 用tqdm包裹executor.map的结果,指定total参数显示进度
    for _ in tqdm(executor.map(some_func, range(100)), total=100):
        pass

3. multiprocessing.Pool+tqdm(另一种标准库方案)

用传统的multiprocessing.Pool配合tqdm也能达成目标,写法稍繁琐一点,但胜在是标准库:

from multiprocessing import Pool
from tqdm import tqdm

def some_func(i):
    # 业务逻辑
    pass

with Pool(processes=4) as pool:
    for _ in tqdm(pool.imap(some_func, range(100)), total=100):
        pass

内容的提问来源于stack exchange,提问作者Adar Cohen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 13:17:46