答案:通过在子进程中调用debugpy.listen()并配置VS Code的launch.json,可实现多进程调试。具体步骤包括:在worker函数中为每个子进程启动debugpy监听不同端口,主进程正常运行;VS Code先启动主进程调试,再手动附加到子进程端口;利用compound配置协同多个调试任务;通过环境变量或日志辅助控制调试行为,从而完成对主进程和子进程的联合调试。

调试Python的多进程应用在VS Code中确实比单进程复杂,因为子进程默认不会被调试器附加。不过通过合理配置和使用debugpy(VS Code Python扩展依赖的调试服务器),你可以实现对主进程和子进程的同时调试。
启用子进程调试的关键:在子进程中手动启动debugger
VS Code默认只调试启动时的主进程。要调试multiprocessing创建的子进程,需要在子进程代码中显式调用debugpy.listen()并等待连接。
基本思路:
示例代码:
立即学习“Python免费学习笔记(深入)”;
import multiprocessing as mp import debugpydef worker_function(data):
子进程中开启调试监听
debugpy.listen(('localhost', 5678 + mp.current_process().pid % 100)) print(f"Worker {mp.current_process().name} waiting for debugger...") debugpy.wait_for_client() # 阻塞直到客户端连接 print(f"Debugger attached to {mp.current_process().name}") # 正常业务逻辑 result = data * 2 print(f"Processed {data} -> {result}") return resultdef main(): debugpy.breakpoint() # 主进程断点 print("Main process started")
with mp.Pool(processes=2) as pool: results = pool.map(worker_function, [1, 2, 3, 4]) print("Results:", results)if name == 'main': main()
配置VS Code launch.json支持多进程调试
你需要一个能复用调试配置的设置,让VS Code可以连接多个进程。
推荐launch.json配置:
{ "version": "0.2.0", "configurations": [ { "name": "Python: 启动主进程", "type": "python", "request": "launch", "program": "${workspaceFolder}/your_script.py", "console": "integratedTerminal", "justMyCode": true, "cwd": "${workspaceFolder}" }, { "name": "Python: 附加到子进程", "type": "python", "request": "attach", "connect": { "host": "localhost", "port": 5678 }, "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "." } ] } ], "compounds": [ { "name": "调试主进程和子进程", "configurations": ["Python: 启动主进程", "Python: 附加到子进程"], "stopAll": false } ] }说明:
- 先运行“启动主进程”配置
- 当子进程打印出“waiting for debugger”时,手动启动多个“附加到子进程”实例(可修改端口适配不同子进程)
- 也可使用脚本自动探测新进程并附加(进阶)
简化调试的小技巧
如果你只是想快速排查问题,可以临时降级为单进程运行:
- 将
Pool换成直接调用函数 - 使用
if __name__ == '__main__':保护确保只有主进程启动debugger - 利用
logging输出替代部分断点,减少调试器依赖
也可以设置环境变量控制是否启用调试:
import os
if os.getenv('ENABLE_DEBUGPY'):
import debugpy
debugpy.listen(5678)
debugpy.wait_for_client()
基本上就这些。虽然不能一键全链路调试所有进程,但通过主动监听+手动附加的方式,已经能在VS Code中有效调试多进程Python应用了。关键是理解每个进程是独立的,必须各自接入调试器。










