VSCode Python运行代码带参数Debug调试和Run运行代码
1.使用VSCode自动生成launch.json文件
1.1 带参数Debug调试
-
点击左侧Run and Debug进入debug界面
-
点击 create a launch.json file创建launch.json配置文件
-
选择
Python Debugger
-
选择Python File with Arguments
-
自动生成launch.json文件
-
查看launch.json文件所在目录
-
添加Python运行参数
配置文件内容如下
{ // 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": "Python Debugger: Current File with Arguments", "type": "debugpy", "request": "launch", "program": "${file}", "console": "integratedTerminal", "args": [ "--name", "squid", "--age", "26", "--gender", "male", "--nationality", "China" ] } ] }
相当于下面的Python运行代码:
python .\main_test2.py --name squid --age 26 --gender male --nationality China
- Debug按钮生成
这里的"name": “Python Debugger: Current File with Arguments”,中的
Python Debugger: Current File with Arguments
就是RUN AND DEBUG的名字。
-
开始Debug
选择需要调试的Python代码文件 -
点击绿色三角箭头或者F5即可debug
这里要注意,开始debug之前需要切换到对应的python文件后在运行。
- Debug结果
可以看到运行结果和使用命令行带参数运行的结果一直
1.2 带参数Run运行
参考1.1 小节。没有设置断点时,程序处于运行状态,直至结束。
设置断点时,点击Continue或者F5、或者取消断点breakpoint运行程序
-
点击左键设置断点
-
Debug到断点处停止
-
点击三角箭头Continue或者F5继续运行至下一个断点或者结束
-
或者再次左键取消断点breakpoint后F5继续运行至下一个断点或者结束
2.使用vpdb库自动生成
2.1 安装vpdb库
pip install vpdb
2.2 使用vpdb库自动生成launch.json文件具体步骤
在命令之前添加vpdb即可。
!!!注意,需要在Linux系统上使用才行
vpdb python ./main_test2.py --name squid --age 26 --gender male --nationality China
-
自动生成launch.json文件
-
参考vscode(右)和vpdb(左)生成的launch.json文件
-
运行结果和vscode生成的文件结果一致
3.添加运行任务
3.1 功能
在VSCode中可以通过tasks.json来配置运行任务,实现一键运行带参数的Python脚本。
tasks.json 文件通常放在 VSCode 项目的 .vscode 目录下,和 launch.json 等配置文件处于同一目录。
对于终端中运行,可以配置tasks.json:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "echo",
"type": "shell",
"command": "/home/iristar/miniconda3/envs/yolov8/bin/python main_test2.py --name squid --age 26 --gender male --nationality China"
}
]
}
现在可以通过“运行任务”来启动带参数的脚本。
3.2 具体设置步骤如下
- 点击Terminal->Configure Tasks…
-
点击Create tasks.json file from template
-
点击选择Others生成tasks.json文件
-
生成tasks.json文件
"label": "echo", // 中的参数自定义。显示运行任务的名称。
"type": "shell", // 表示该任务将通过调用 shell 命令来运行。
"command": "echo Hello" // 为代码运行命令
// 如下。
"command": "python main_test2.py --name squid --age 26 --gender male --nationality China"
其中,python需要改为具体路径
"command": "/home/iristar/miniconda3/envs/yolov8/bin/pythonmain_test2.py --name squid --age 26 --gender male --nationality China"
3.3 使用方式如下
-
点击Terminal->Run Tasks…
-
选择刚才创建的tasks.json里面的echo任务
这里的echo任务和tasks.json文件里面的"label": "echo"中的echo一致。
-
选择Continue without scanning the task output
-
显示指定 Python 解释器路径防止出错
-
运行结果