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

Jupyter中使用multiprocess池调用子函数遇NameError的解决咨询

Jupyter中multiprocess进程池调用外部函数报NameError的解决方法

问题原因

Jupyter笔记本的交互式运行环境和普通Python脚本不同:子进程启动时不会像脚本那样重新导入主模块,而是尝试复制父进程的命名空间,但顶层定义的外部函数(比如test_int)无法在子进程中被正确识别——multiprocess进程池依赖函数的可序列化与可导入性,Jupyter的命名空间机制破坏了这个逻辑。

简洁解决方法

方法1:将函数封装到独立模块(跨平台通用)

把需要被调用的子函数放到单独的.py文件中,让子进程可以通过模块导入的方式获取函数,这是最可靠的跨平台方案。

  1. 创建utils.py文件,写入子函数:
def test_int():
    return 1
  1. 在Jupyter笔记本中导入并使用:
import multiprocess as mp
from utils import test_int

def test():
    return test_int()

if __name__ == '__main__':  
    with mp.Pool(20) as pool:
        for _ in range(20):
            res = pool.apply_async(test, [])
            print(res.get())

方法2:使用fork启动方式(仅Linux/macOS可用)

在类Unix系统中,设置进程启动方式为fork,它会直接复制父进程的完整内存空间,包括所有顶层定义的函数,不需要额外的模块导入。

import multiprocess as mp

def test_int():
    return 1

def test():
    return test_int()

if __name__ == '__main__':  
    mp.set_start_method('fork')  # 仅支持Linux/macOS
    with mp.Pool(20) as pool:
        for _ in range(20):
            res = pool.apply_async(test, [])
            print(res.get())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 17:52:45