【jupyter 使用多进程方案】

可选择的方案:

  1. pathos.multiprocessing
  2. joblib.Parallel

来写的 Jupyter Notebook 兼容版本 示例。


✅ 方法一:使用 pathos.multiprocessing(Jupyter友好)

python 复制代码
from pathos.multiprocessing import ProcessingPool as Pool
from tqdm import tqdm

def process_image(img_path, output_path):
    # 你的图像处理逻辑,比如保存图像到 output_path
    # 示例代码如下(请根据你实际处理内容修改):
    from PIL import Image
    img = Image.open(img_path)
    img.save(output_path)
    return output_path

# 构造参数列表(每个是一个元组)
args = [(img_path, output_path / img_path.name) for img_path in img_paths]

# 初始化 Pool 并并行处理
pool = Pool()  # 默认使用 CPU 核心数

# tqdm 不支持 map 直接用,写成 list
results = list(tqdm(pool.uimap(lambda args: process_image(*args), args), total=len(args)))

🔑 特点:

  • 支持在 Jupyter 中直接运行;
  • 不需要 if __name__ == "__main__"
  • 支持传多个参数(通过 *args 拆包);
  • 使用 uimap() 可以有 tqdm 进度条(imap 带顺序,map 会等全部完成)。

✅ 方法二:使用 joblib.Parallel(适合CPU密集,稳定)

python 复制代码
from joblib import Parallel, delayed
from tqdm import tqdm

def process_image(img_path, output_path):
    from PIL import Image
    img = Image.open(img_path)
    img.save(output_path)
    return output_path

# tqdm 进度条用在参数上
results = Parallel(n_jobs=-1)(
    delayed(process_image)(img_path, output_path / img_path.name)
    for img_path in tqdm(img_paths)
)

🔑 特点:

  • n_jobs=-1 表示使用所有可用核心;
  • 同样支持多个参数;
  • 在 Jupyter 运行稳定,依赖 loky 后端;
  • 避免了 pickle 报错。

📦 安装依赖

如果你没有安装 pathosjoblib

bash 复制代码
pip install pathos joblib

✅ 总结对比

特性 pathos joblib
Jupyter兼容
多参数传递 ✅(tuple 拆包) ✅(delayed(f)(...)
支持 tqdm ✅(配合 uimap ✅(在 for 循环外)
稳定性/文档支持 中(社区较活跃) 高(广泛用于 sklearn 等)
推荐使用场景 函数自由写、调试方便 大批量 CPU 密集任务
相关推荐
IVEN_6 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang7 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮7 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling7 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮10 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽11 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers