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

Windows环境Jupyter Lab中multiprocessing.Process无法正常启动

Windows下Jupyter Lab中multiprocessing.Process子进程无输出的原因及解决办法

问题描述

我刚接触multiprocessing库,编写了一段使用Process的简单代码,该代码在Colab上运行正常,但在本地Windows系统通过Anaconda启动的Jupyter Lab中运行时,子进程的输出未出现。

代码如下:

from multiprocessing import Process
def teste(a):
    print(a)
if __name__ == '__main__':
    print('ok')
    p = Process(target=teste, args=(1,))
    p.start()
    p.join()
    print('b')
    print(p)

Colab运行结果:

ok
1
b
Process name='Process-10' pid=3765 parent=493 stopped exitcode=0

本地Windows运行结果:

ok
b
Process name='Process-10' pid=27844 parent=10844 stopped exitcode=0

看起来p.start()未产生预期输出,这是什么原因?

原因分析

这是Windows进程模型和Jupyter执行环境的特性共同导致的:

  • Windows的spawn启动机制:Windows下multiprocessing默认用spawn方式创建子进程,会启动新的Python解释器并重新导入当前脚本。但Jupyter的代码单元格并非独立脚本文件,子进程无法正确加载teste函数定义;即使能加载,Jupyter的输出捕获机制也无法获取子进程的print输出,导致看不到1的打印结果。
  • 子进程实际已正常执行:从进程信息的exitcode=0可以看出,子进程已经正常退出,只是输出没被捕获到。

解决办法

1. 将函数放到独立模块中导入

创建一个名为utils.py的文件,写入:

def teste(a):
    print(a)

然后在Jupyter单元格中运行:

from multiprocessing import Process
from utils import teste

if __name__ == '__main__':
    print('ok')
    p = Process(target=teste, args=(1,))
    p.start()
    p.join()
    print('b')
    print(p)

2. 捕获子进程输出到文件验证

修改代码让子进程把内容写入文件,确认是否执行:

from multiprocessing import Process

def teste(a):
    with open('subprocess_log.txt', 'w') as f:
        f.write(str(a))

if __name__ == '__main__':
    print('ok')
    p = Process(target=teste, args=(1,))
    p.start()
    p.join()
    print('b')
    print(p)
    # 读取文件查看结果
    with open('subprocess_log.txt', 'r') as f:
        print('子进程输出:', f.read())

3. 使用Pool替代Process(更适配Jupyter)

from multiprocessing import Pool

def teste(a):
    print(a)
    return a

if __name__ == '__main__':
    print('ok')
    with Pool(1) as pool:
        result = pool.apply(teste, args=(1,))
    print('b')
    print('子进程返回结果:', result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:10:25