VSCode + Python + Shell 调试 (Debug) : debugpy

场境: 使用VSCode对一个用Shell脚本启动的Python程序进行Debug.

1. debugpy安装

在激活了相应的conda虚拟环境后,安装debugpy库:

pip install debugpy

2. 查看可用端口

运行

for port in {5000..6000}; do
    (echo > /dev/tcp/localhost/$port) >/dev/null 2>&1 || echo "$port is free"
done

查看5000-6000之间的可用端口,例如5555

3. launch.json 配置

在VSCode按Ctrl+Shift+P, 输入Debug: Add Configuration 新建一个launch.json(或者直接打开launch.json)
编辑以下内容并保存

{
	"version": "0.2.0",
	"configurations": [
		{
			"name": "[这里更换为任意名称]",
			"type": "python",
			"request": "attach",
			"connect": {
				"host": "localhost",
				"port": [这里填写可用端口,如5555]
			}
		}
	]
}

4. Shell

使用Shell 启动Python
只需要稍微对原来的Shell进行编辑,
例如原来的Shell是

python [NAME].py --arg1 "arg" --arg2 "123" 

只需要在python[NAME].py之间加入 -m debugpy --listen [端口号]
即:

python -m debugpy --listen 5555[此处更换为你可用的端口号] [NAME].py --arg1 "arg" --arg2 "123" 

5. 运行

按照通常方式运行shell即可

posted @ 2024-10-19 16:50  Mactor  阅读(1533)  评论(0)    收藏  举报