VSCode 运行和调试代码
以调试 hello.py 为例演示检查与选择 Python 3 解释器、通过行首红点或 F9 设置断点、按 F5 启动调试器、悬停与变量视图查看局部状态以及继续执行和高级调试能力。
学完这一章,你能够
- 以调试 hello.py 为例演示检查与选择 Python 3 解释器、通过行首红点或 F9 设置断点、按 F5 启动调试器、悬停与变量视图查看局部状态以及继续执行和高级调试能力。
准备 Python 3 解释器与设置断点
VS Code 原生内置 Node.js 运行与调试支持,而安装官方 Python 扩展后同样可以直接调试 Python 程序。调试前节编写的 `hello.py` 前,需确认本机已安装 Python 3;若编辑器未检测到可用解释器,右下角会弹出提醒,点击 `Select Interpreter(选择解释器)` 即可通过命令面板指定已有解释器路径或前往安装。
打开 `hello.py`,将光标移动到 `print` 语句所在行,点击行号左侧边距浮现的暗红圆点或直接按下 `F9` 键即可设置断点。设置成功后边距会亮起实心红点,程序执行到该行前会自动暂停以便检查现场。
启动调试会话、观察变量与继续执行
按下 `F5` 启动调试会话,在弹出的调试器列表中依次选择 “Python 调试器(Python Debugger)” 与 “Python 文件(运行当前 Python 文件)”,调试器即会拉起程序运行。
程序命中断点后暂停于 `print` 行:此时将鼠标悬停在编辑器中的 `name` 变量上,或在左侧调试面板的“变量视图(Variables View)”中均可实时查看其值(`"VS Code"`)。检查完毕后点击顶部调试工具栏的 `Continue(继续)` 按钮或再次按 `F5`,程序即继续执行至结束。除此之外,VS Code 还支持监视变量(Watch)、条件断点(Conditional Breakpoints)及 `.vscode/launch.json` 启动配置。本站离线脚本已校验 `launch.json` 结构,并用 Python 标准库 `bdb` 在临时 `hello.py` 第 2 行实测命中真实断点、读取局部变量 `name == "VS Code"` 并继续执行输出 `Hello, VS Code`。
运行 .vscode/launch.json 配置校验与 Python 标准库 bdb 真实断点暂停/变量检查实验
展开查看收起
"""Offline VS Code launch.json config & real Python bdb breakpoint debugger verifier for Ch17."""
import bdb
import io
import json
import sys
import tempfile
from contextlib import redirect_stdout
from pathlib import Path
VERSION = "CPython 3.12.14 offline VS Code launch.json & bdb breakpoint verifier"
def check(name, summary, expected, actual):
return {
"name": name,
"summary": summary,
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
class TraceDebugger(bdb.Bdb):
def __init__(self, target_file: str):
super().__init__()
self.target_file = self.canonic(target_file)
self.stops = []
def user_line(self, frame):
if self.canonic(frame.f_code.co_filename) == self.target_file and self.break_here(frame):
self.stops.append({
"lineno": frame.f_lineno,
"func": frame.f_code.co_name,
"name_var": frame.f_locals.get("name"),
})
self.set_continue()
def main():
cases = []
# Case 1: .vscode/launch.json Python debug schema & interpreter selection check
launch_cfg = {
"version": "0.2.0",
"configurations": [
{
"name": "Python Debugger: Current File",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
}
],
}
cfg = launch_cfg["configurations"][0]
cases.append(
check(
"launch_json_and_interpreter_selection",
"Verify .vscode/launch.json Python Current File configuration and Python 3 interpreter version",
{
"schema_version": "0.2.0",
"debugger_type": "debugpy",
"request": "launch",
"program_macro": "${file}",
"python_major_is_3": True,
},
{
"schema_version": launch_cfg["version"],
"debugger_type": cfg["type"],
"request": cfg["request"],
"program_macro": cfg["program"],
"python_major_is_3": sys.version_info.major == 3,
},
)
)
# Case 2: Real bdb breakpoint pause on print() line, inspect `name` variable, then Continue
source = (
"def say_hello(name):\n"
' print("Hello, " + name)\n'
'say_hello("VS Code")\n'
)
with tempfile.TemporaryDirectory() as tmp:
py_file = Path(tmp) / "hello.py"
py_file.write_text(source, encoding="utf-8")
filename = str(py_file)
dbg = TraceDebugger(filename)
err = dbg.set_break(filename, 2)
assert err is None, err
buf = io.StringIO()
code_obj = compile(source, filename, "exec")
with redirect_stdout(buf):
dbg.run(code_obj, {}, {})
cases.append(
check(
"bdb_breakpoint_pause_and_inspect",
"Verify real Python bdb breakpoint hit on line 2, local variable name=='VS Code', and continue output",
{
"breakpoint_hits": 1,
"paused_line": 2,
"paused_func": "say_hello",
"inspected_name": "VS Code",
"final_stdout": "Hello, VS Code",
},
{
"breakpoint_hits": len(dbg.stops),
"paused_line": dbg.stops[0]["lineno"],
"paused_func": dbg.stops[0]["func"],
"inspected_name": dbg.stops[0]["name_var"],
"final_stdout": buf.getvalue().strip(),
},
)
)
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
按 `F9` 在光标所在行设置或取消断点;按 `F5` 启动调试会话,并在断点暂停后继续执行程序。