在 VSCode 中调试 Python 时如何激活虚拟环境

admin
2025-01-23 / 0 评论 / 7 阅读 / 正在检测是否收录...

1. 创建虚拟环境

python -m venv venv

2. 选择虚拟环境解释器

  1. 打开 VSCode。
  2. 按下 Ctrl+Shift+P(macOS 是 Cmd+Shift+P)。
  3. 输入并选择 “Python: Select Interpreter”。
  4. 选择你的虚拟环境解释器,例如:
  5. Linux/macOS: ./venv/bin/python
  6. Windows: ./venv/Scripts/python.exe

3. 配置调试文件

为了确保调试时使用虚拟环境,可以修改 VSCode 的 launch.json 文件:

  1. 点击左侧 “运行和调试” 图标,或者按下 Ctrl+Shift+D。
  2. 点击顶部的 “创建 launch.json 文件”,选择 Python。
  3. 编辑生成的 launch.json 文件,确保指向虚拟环境解释器:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: 当前文件",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "python": "${workspaceFolder}/venv/bin/python"  // Linux/macOS
            // 或
            // "python": "${workspaceFolder}\\venv\\Scripts\\python.exe"  // Windows
        }
    ]
}

4. 手动激活虚拟环境

.\venv\Scripts\activate
source venv/bin/activate
0

评论 (0)

取消