如何为VSCode调试(F5)和运行(CTRL+F5)配置不同launch.json参数?
解决VSCode调试与运行自动切换PYTHONOPTIMIZE的方案
方案1:在launch.json中配置双启动项
直接在.vscode/launch.json里新增两个独立配置,分别对应调试和无调试运行场景,设置不同的PYTHONOPTIMIZE值:
{ "version": "0.2.0", "configurations": [ { "name": "Debug: Tool (PYTHONOPTIMIZE=0)", "type": "debugpy", "program": "path_to_my/python_tool.py", "args": [ "--some-property", "argument", "--another-property", "lalala", "--this-list-goes", "On and On and On..." ], "env": { "PYTHONOPTIMIZE": "0" } }, { "name": "Run: Tool (PYTHONOPTIMIZE=1)", "type": "debugpy", "program": "path_to_my/python_tool.py", "args": [ "--some-property", "argument", "--another-property", "lalala", "--this-list-goes", "On and On and On..." ], "env": { "PYTHONOPTIMIZE": "1" }, "request": "launch" } ] }
使用方式:
- 按F5前,在左侧“运行和调试”面板的下拉菜单选中
Debug: Tool (PYTHONOPTIMIZE=0),启动调试 - 按Ctrl+F5前,切换到
Run: Tool (PYTHONOPTIMIZE=1),启动无调试运行
嫌切换麻烦的话,可以给两个配置绑定自定义快捷键:打开键盘快捷方式(Ctrl+K Ctrl+S),搜索debug.selectandstart和debug.runwithoutdebugging,分别绑定到你习惯的快捷键,或者直接给特定配置绑定启动命令。
方案2:用Tasks.json实现快捷键直接触发
创建.vscode/tasks.json,定义两个独立任务分别处理调试和运行:
{ "version": "2.0.0", "tasks": [ { "label": "Debug Tool", "type": "python", "command": "${command:python.debug.activeFile}", "args": [ "--some-property", "argument", "--another-property", "lalala", "--this-list-goes", "On and On and On..." ], "env": { "PYTHONOPTIMIZE": "0" }, "problemMatcher": [] }, { "label": "Run Tool", "type": "shell", "command": "python path_to_my/python_tool.py", "args": [ "--some-property", "argument", "--another-property", "lalala", "--this-list-goes", "On and On and On..." ], "env": { "PYTHONOPTIMIZE": "1" }, "problemMatcher": [] } ] }
然后给任务绑定快捷键:打开键盘快捷方式,添加如下配置:
{ "key": "f5", "command": "workbench.action.tasks.runTask", "args": "Debug Tool" }, { "key": "ctrl+f5", "command": "workbench.action.tasks.runTask", "args": "Run Tool" }
之后按F5直接启动调试任务,Ctrl+F5直接启动运行任务,无需手动切换配置。
方案3:Python代码内自动判断(极简版)
如果不想修改VSCode配置,可以在python_tool.py开头加入逻辑,自动识别运行模式并切换环境变量:
import sys import os # 判断是否处于debugpy调试环境 if sys.gettrace() is not None or "DEBUGPY_SESSION_ID" in os.environ: os.environ["PYTHONOPTIMIZE"] = "0" else: os.environ["PYTHONOPTIMIZE"] = "1" # 后续业务代码...
注意:PYTHONOPTIMIZE在Python启动时就生效,这种代码内设置的方式可能对部分依赖启动时优化逻辑的场景有影响,需要测试验证后使用。
内容的提问来源于stack exchange,提问作者Grzegorz Lippe
相关产品推荐
相关产品推荐

