一个计算机技术爱好者与学习者

0%

VSCode配置Python Debug

1. 前言

本文学习在VSCode中配置Python Debug的方法,备忘。

2. 配置调试

2.1. 打开 laungch.json

方法一:
直接打开 .vscode/launch.json 文件

方法二:
点击VSCode左侧带虫子的三角形,进入RUN AND DEBUG页面,点击齿轮,打开 launch.json 文件

2.2. 配置 launch.json

假设程序启动命令为 python startup.py "write a cli snake game",那么配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "startup debug",
"type": "python",
"request": "launch",
"program": "startup.py",
"cwd": "${workspaceFolder}",
"args": [
"write a cli snake game"
],
"env": {
"OPENAI_API_KEY": "sk-xxx"
},
"console": "integratedTerminal",
"justMyCode": false
}
]
}

假设每个脚本都能直接运行 python xxx.py,那么配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"version": "0.2.0",
"configurations": [
{
"name": "python debug",
"type": "python",
"request": "launch",
"program": "${file}",
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"justMyCode": false
}
]
}

注意:justMyCode 要配置为 false,否则第三方库没法打断点。

3. 切换Python解释器

1、点击 command+shift+P,打开快捷配置。

2、输入 Python: Select Interpreter,选择当前代码需要的解释器版本。

注意:如果是使用pyenv安装的python环境,请选择带有版本的路径,例如 ~/.pyenv/versions/3.9.7/bin/python ;不要选择当前在用python的路径 ~/.pyenv/shims/python,否则会找不到pip安装的包。

4. 开始调试

1、点击VSCode左侧带虫子的三角形,进入RUN AND DEBUG页面

2、点击齿轮左边的三角形,即可进入调试,这时我们就可以打断点看程序的执行了。