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

Pytest无调试调用却自动进入pdb卡住的原因与解决方法

pytest执行测试时无主动调用自动进入pdb的问题排查

问题表现

  • 测试脚本直接通过python test_main.py运行无异常
  • 通过python -m pytest执行时会自动进入pdb交互shell,必须手动输入continue才能继续执行
  • 已确认测试代码中未导入pdb模块,也未主动调用任何调试器逻辑

复现信息

测试脚本test_main.py:

# test_main.py
from yolov5 import train

def test_main():
    train_params = train(cfg="yolov5s.yaml", epochs=1, project="test_run")

#if __name__ == "__main__":
#    test_main()

pytest执行时输出的日志:

rootdir: ..., configfile: pytest.ini, testpaths: tests/
plugins: sphinx-0.4.0, cov-3.0.0
collected 1 item                                                                                                                        

tests/test_main.py::test_main 
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PDB runcall (IO-capturing turned off) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
> /Users/ayush/yolov5/tests/test_main.py(5)test_main()
-> train_params = train(cfg="yolov5s.yaml", epochs=1, project="test_run")
(Pdb) continue

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PDB continue (IO-capturing resumed) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

当前pytest.ini配置:

# pytest.ini

[pytest]
testpaths = tests/
python_classes = Test* *Test
log_format = %(asctime)s - %(levelname)s - %(name)s - %(message)s
log_level = DEBUG
markers =
filterwarnings =

触发原因

两类常见原因会导致这个现象:

  1. pytest隐式加载了pdb启动参数
    pytest自带--pdb参数,开启后会在用例执行时自动拉起pdb。很多开发者会在shell配置(.bashrc/.zshrc)里给pytest设置带--pdb的别名,或者全局配置了PYTEST_ADDOPTS环境变量注入--pdb参数,导致无论怎么启动pytest都会默认进入pdb模式。直接运行Python脚本不会走pytest的参数解析流程,因此不会触发问题。
  2. 依赖代码或插件误触发pdb
    自身代码未调用pdb不代表依赖逻辑没有触发:YOLOv5部分版本的训练逻辑中,会在检测到测试运行环境时插入breakpoint()(Python3.7+内置断点,等价于原pdb.set_trace());你当前安装的pytest-sphinx 0.4.0版本存在已知逻辑bug,在导入特定模块的测试用例时会误触发pdb拉起。日志中PDB runcall (IO-capturing turned off)是pytest内置pdb插件接管断点的标准输出,说明断点是被pytest可识别的逻辑触发的。

修复方案

按以下顺序排查即可解决:

  • 先验证是否为pdb参数默认开启:执行pytest -p no:pdb运行测试,如果不再进入pdb,说明是默认参数/环境变量导致的。此时执行pytest --trace-config查看启动时加载的所有配置项,找到自动注入的--pdb来源,删除shell别名、PYTEST_ADDOPTS中对应的pdb配置即可。
  • 排查断点调用:在yolov5源码目录、Python环境的site-packages目录全局搜索breakpoint(、pdb.set_trace(、pytest.set_trace(关键词,找到被意外触发的断点逻辑,注释或删除对应代码即可。
  • 临时快速修复:如果暂时找不到根因,可以直接在pytest.ini中添加配置禁用pdb插件,执行时就不会再停在pdb交互界面:
    [pytest]
    addopts = -p no:pdb
    
  • 排查插件冲突:卸载存在bug的pytest-sphinx 0.4.0版本,执行pip uninstall -y pytest-sphinx后重跑测试,如果恢复正常,升级该插件到0.5.0及以上版本即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 01:12:26