已激活虚拟环境后,如何通过VS Code的launch.json运行Python文件?
用VS Code的launch.json实现虚拟环境运行Python文件
步骤1:打开launch.json配置
- 将
folder1设为VS Code当前工作区 - 按
Ctrl+Shift+D打开运行和调试面板 - 点击「创建launch.json文件」,选择Python环境
步骤2:配置launch.json内容
替换自动生成的配置为以下代码,按需调整路径:
{ "version": "0.2.0", "configurations": [ { "name": "Virtual Env Run file1.py", "type": "python", "request": "launch", "program": "${workspaceFolder}/file1.py", // 固定运行file1.py,也可用${file}运行当前打开的文件 "python": "${workspaceFolder}/.venv/bin/python3.12", // 指定虚拟环境的Python解释器 "console": "integratedTerminal", "cwd": "${workspaceFolder}" } ] }
关键参数说明
python:直接指向虚拟环境内的python3.12可执行文件,VS Code会自动使用该环境,无需手动激活program:如果要固定运行file1.py就写相对路径;用${file}则会运行当前编辑的Python文件console:设为integratedTerminal,程序会在VS Code集成终端中运行,和你手动执行的终端环境完全一致
运行测试
保存配置后,打开file1.py,点击运行面板的绿色启动按钮(或按F5),就能看到程序按预期运行,效果和手动执行python3.12 file1.py一致
内容的提问来源于stack exchange,提问作者Aseem
相关产品推荐
相关产品推荐

