求助:VS Code中调试含多进程的Jupyter Notebook
问题描述
在Jupyter Notebook中使用multiprocessing的Pool缩短处理时间,但在Visual Studio Code中调试时遇到问题:
- 首先弹出错误:
Couldn't find a debug adapter descriptor for debug type 'Python Kernel Debug Adapter'
(extension might have failed to activate)
- 随后每个子进程都会提示:
Failed to launch debugger for child process X
相关代码
Jupyter单元格代码:
from multiprocessing import Pool from func import x with Pool(4) as p: results = p.map(x, [1,2,3,4]) for i in results: # 断点 print(i)
配套的func.py文件:
def x(y): return y
已尝试过的无效方法:按照VS Code文档建议添加以下代码,但问题依旧:
import debugpy debugpy.debug_this_thread()
环境信息
Windows 10、Python 3.11、VS Code 1.74.1
请问能否在VS Code中调试这类使用multiprocessing的Jupyter Notebook?
可行调试方案
目前VS Code的Jupyter调试器对multiprocessing子进程的支持存在局限性,但可以通过以下两种方式解决:
方法一:指定spawn上下文并初始化子进程调试器
Windows系统下multiprocessing默认用spawn启动子进程,手动指定上下文并在子进程中初始化调试器,能让VS Code捕获到子进程:
修改Jupyter单元格代码如下:
from multiprocessing import get_context from func import x import debugpy # 主进程启动调试监听 if not debugpy.is_client_connected(): debugpy.listen(('localhost', 5678)) def init_debugger(): # 子进程连接调试器 debugpy.connect(('localhost', 5678)) # 使用spawn上下文创建Pool,绑定初始化函数 with get_context('spawn').Pool(4, initializer=init_debugger) as p: results = p.map(x, [1,2,3,4]) for i in results: print(i)
操作步骤:
- 在
func.py的x函数内添加断点 - 运行Jupyter单元格
- 在VS Code的调试面板中创建Python: Attach配置,端口设为5678,启动该调试配置,即可调试子进程。
方法二:转为普通Python脚本调试
如果不需要在Notebook环境中调试,将核心逻辑提取为普通.py文件,VS Code的Python调试器对multiprocessing的支持更完善:
创建main.py文件:
from multiprocessing import Pool from func import x if __name__ == '__main__': with Pool(4) as p: results = p.map(x, [1,2,3,4]) for i in results: # 断点 print(i)
直接在VS Code中调试该脚本,主进程和子进程的断点都能正常触发。
注意事项
- 不要在Jupyter Notebook的默认调试会话中使用
Pool,Notebook内核与调试器的交互方式不兼容子进程调试。 - 使用
debugpy时,确保主进程和子进程的调试端口一致,且端口未被其他程序占用。
内容的提问来源于stack exchange,提问作者Yui

