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

Jupyter Notebook中Python time模块在多进程函数内失效问题咨询

Python多进程中函数内time未定义的原因及解决方法

问题描述

我是Python新手,在Jupyter Notebook中学习多进程时遇到了异常问题。以下是我的代码:

from multiprocess import Process
import time
def longSquare(num,results):
    print('Check!')
    time.sleep(1)
    print(num**2)
results={}
time.sleep(1)
print('Check1')
p1=Process(target=longSquare, args=(1,results))
time.sleep(1)
print('Check2')
p2=Process(target=longSquare, args=(2,results))

p1.start()
p2.start()

p1.join()
p2.join()

运行后命令提示符报错:
line 3, in longSquare NameError: name 'time' is not defined. Did you forget to import 'time'?

输出内容为:
Check1
Check2

为何函数外的time.sleep(1)可正常运行,函数内的却不行?

原因分析

这是因为多进程的内存空间完全独立:

  • 主进程里的import time仅在主进程内存中生效,子进程不会直接继承主进程已导入的模块(尤其在Jupyter Notebook的交互式环境下,子进程无法正确获取主进程的模块导入状态)。
  • 函数外的time.sleep(1)在主进程中执行,能正常调用模块;而longSquare函数是在子进程中运行的,子进程未导入time模块,因此触发NameError。

另外你代码里的from multiprocess import Process存在拼写错误,正确模块名是multiprocessing,这也是潜在问题。

解决方法

  • 在子进程执行的函数内部导入time模块:
    修改函数,把import time放到longSquare内部,确保子进程运行时能加载模块:
    def longSquare(num,results):
        import time
        print('Check!')
        time.sleep(1)
        print(num**2)
    
  • 修正多进程模块的拼写:
    将from multiprocess import Process改为from multiprocessing import Process,否则会先出现模块找不到的错误。

额外提示

你用字典results传递进程间结果的方式是无效的,因为子进程内存独立,修改子进程内的字典不会同步到主进程。如果需要进程间传递数据,建议使用multiprocessing.Queue或Manager类。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 00:52:09