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

如何让Python调试器及VSCode中pytest测试退出前自动暂停?

Python调试器自动在退出前暂停的方法

通用Python方案

无需手动设置断点或添加临时暂停语句,可借助atexit模块注册退出回调,在程序结束时自动启动调试器:

import atexit
import pdb

def debug_before_exit():
    pdb.set_trace()

atexit.register(debug_before_exit)

将这段代码放在项目入口文件或全局配置文件中,程序正常退出或因未捕获异常退出时(强制终止除外),都会自动进入pdb交互模式,此时可查看所有变量状态。

如果只想在调试模式下触发,避免正常运行时暂停,可增加调试状态检测:

import atexit
import pdb
import sys

def debug_before_exit():
    # 仅当调试器已附加时触发
    if sys.gettrace() is not None:
        pdb.set_trace()

atexit.register(debug_before_exit)

VSCode中调试pytest测试的实现方法

在VSCode中调试pytest时,无需修改测试文件,只需在项目根目录创建conftest.py文件,加入上述带调试检测的代码即可:

# conftest.py
import atexit
import pdb
import sys

def pause_on_test_exit():
    if sys.gettrace() is not None:
        pdb.set_trace()

atexit.register(pause_on_test_exit)

pytest会自动加载conftest.py中的配置,当启动VSCode调试会话时(比如选择"Python: pytest"调试配置),所有测试运行结束后,调试器会自动暂停,此时可在VSCode的调试面板中查看变量、调用栈等信息。

另外,可通过修改VSCode的调试配置(launch.json)确保调试器能正确捕获pdb断点:

  1. 打开调试面板,创建或编辑launch.json,选择pytest配置模板
  2. 确保配置中包含"justMyCode": false,让调试器能处理pdb触发的暂停:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: pytest",
            "type": "python",
            "request": "launch",
            "module": "pytest",
            "justMyCode": false,
            "args": [
                "${file}"
            ]
        }
    ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:15:42