Visual Studio Code(VS Code)作为一款轻量级但功能强大的代码编辑器,凭借其出色的Python调试功能,已成为众多开发者的首选工具。本文将详细介绍如何在VS Code中配置和使用Python调试器,帮助您快速定位和解决代码问题。
在开始调试之前,请确保您已完成以下准备工作:
VS Code使用launch.json
文件来配置调试参数:
生成的launch.json
文件可能如下:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}
x > 5
)或命中次数条件对于Web框架,需要特殊配置:
{
"name": "Python: Django",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/manage.py",
"args": ["runserver"],
"django": true
}
ptvsd
:pip install ptvsd
import ptvsd
ptvsd.enable_attach(address=('0.0.0.0', 5678))
ptvsd.wait_for_attach() # 可选,阻塞直到连接
launch.json
:{
"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"host": "远程IP",
"port": 5678
}
VS Code支持直接调试pytest/unittest:
{
"name": "Python: Pytest",
"type": "python",
"request": "launch",
"module": "pytest",
"args": ["${file}"]
}
debug.inlineValues
,可在代码旁边直接看到变量值"subProcess": true
配置可调试子进程{
"name": "Python: Profile",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"args": [],
"profile": true
}
断点不被命中:
导入错误:
launch.json
中添加"env": {"PYTHONPATH": "${workspaceFolder}"}
调试速度慢:
debugpy
VS Code提供的Python调试工具链既强大又灵活,从简单的脚本到复杂的Web应用都能提供良好的调试体验。通过熟练掌握本文介绍的各种调试技巧,您将能够显著提高问题定位和修复的效率,让开发过程更加顺畅。
随着VS Code和Python扩展的持续更新,建议定期查看官方文档以了解最新功能和改进。Happy debugging!