Python3.9中如何在Hypercorn进程内使用ipdb断点调试?
问题:Python 3.9下Hypercorn进程内无法使用ipdb调试
我使用Python 3.9时,无法在Hypercorn进程内通过ipdb.set_trace()进行调试,但该操作在Python 3.7中可正常运行。
我的代码:
#!/usr/bin/env python3 import ipdb async def app(scope, receive, send): ipdb.set_trace() # DEBUG
执行命令hypercorn hello_world:app时,出现如下错误信息:
❯ hypercorn hello_world:app --Return-- None > /home/alper/trade_bot/bot/hello_world.py(7)app() 5 6 async def app(scope, receive, send): ----> 7 ipdb.set_trace() # DEBUG ipdb> [2024-11-25 16:07:33 +0000] [1228742] [WARNING] ASGI Framework Lifespan error, continuing without Lifespan support [2024-11-25 16:07:33 +0000] [1228742] [INFO] Running on http://127.0.0.1:8000 (CTRL + C to quit) --Return-- None > /home/alper/trade_bot/bot/hello_world.py(7)app() 5 6 async def app(scope, receive, send): ----> 7 ipdb.set_trace() # DEBUG ipdb> [2024-11-25 16:07:35 +0000] [1228742] [ERROR] Error in ASGI Framework Traceback (most recent call last): File "\/home/alper/venv/lib/python3.9/site-packages/hypercorn/asyncio/task_group.py", line 27, in _handle await app(scope, receive, send, sync_spawn, call_soon) File "\/home/alper/venv/lib/python3.9/site-packages/hypercorn/app_wrappers.py", line 34, in __call__ await self.app(scope, receive, send) File "\/home/alper/trade_bot/bot/hello_world.py", line 7, in app ipdb.set_trace() # DEBUG File "\/usr/lib/python3.9/bdb.py", line 92, in trace_dispatch return self.dispatch_return(frame, arg) File "\/usr/lib/python3.9/bdb.py", line 154, in dispatch_return if self.quitting: raise BdbQuit bdb.BdbQuit
此时ipdb>提示符无法接收c、n等调试指令,请问如何在Hypercorn进程内实现断点调试?
解决方案
方法1:改用异步版ipdb调试入口
Hypercorn是异步IO服务器,同步的ipdb.set_trace()会与事件循环冲突,导致交互异常。替换为异步调试入口即可:
#!/usr/bin/env python3 import ipdb async def app(scope, receive, send): await ipdb.asyncio.set_trace() # 使用异步版调试入口
执行原启动命令,ipdb>提示符即可正常接收调试指令。
方法2:禁用Hypercorn多进程模式
Hypercorn默认启动多进程,调试器在多进程环境下会出现交互紊乱。指定单进程运行即可避免该问题:
hypercorn --workers 1 hello_world:app
配合原同步ipdb.set_trace()使用,即可正常调试。
方法3:使用远程调试工具debugpy
如果上述方法仍有问题,可采用远程调试方案:
- 安装debugpy:
pip install debugpy
- 在代码中添加调试监听:
#!/usr/bin/env python3 import debugpy # 开启远程调试监听,端口可自定义 debugpy.listen(("0.0.0.0", 5678)) print("等待调试器连接...") debugpy.wait_for_client() async def app(scope, receive, send): # 可直接在IDE中设置断点,或在此处编写调试逻辑 pass
- 通过PyCharm、VS Code等IDE连接到
localhost:5678,即可正常调试异步代码。
内容的提问来源于stack exchange,提问作者alper
相关产品推荐
相关产品推荐

