You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS Code集成终端激活conda环境滞后,代码先经本地Python执行

VS Code运行Python时未直接激活选中Conda虚拟环境的问题

问题现象

使用Miniconda3创建DL虚拟环境后,在VS Code底部状态栏切换至该环境并运行Python文件时:

  • 集成终端优先调用本地Python解释器执行代码,过程中闪过CMD窗口
  • 终端随后自动执行激活命令(但错误输出中实际激活的是base环境而非选中的DL环境)
  • 实际终端输出:
PS D:\snow\file\postGra> python -u "d:\snow\file\postGra\test.py"
hello
PS D:\snow\file\postGra> D:/snow/sw/miniconda3/Scripts/activate
PS D:\snow\file\postGra> conda activate base
(base) PS D:\snow\file\postGra> 
  • 预期终端输出:
(DL) PS D:\snow\file\postGra> python -u "d:\snow\file\postGra\test.py"
hello

已尝试的无效操作

  • 重装Windows 10系统
  • 重装VS Code及Miniconda3
  • 将集成终端更换为Git Bash

解决方案

1. 确认VS Code Python解释器绑定

打开命令面板(Ctrl+Shift+P),执行Python: Select Interpreter,确保选中的是DL环境的Python可执行文件路径(示例:D:/snow/sw/miniconda3/envs/DL/python.exe)。

同时检查工作区.vscode/settings.json,添加或修改以下配置:

{
    "python.pythonPath": "D:/snow/sw/miniconda3/envs/DL/python.exe",
    "python.terminal.activateEnvironment": true,
    "python.terminal.activateEnvInCurrentTerminal": true,
    "python.terminal.executeInFileDir": false
}

2. 修复Conda的PowerShell初始化

  1. 打开Anaconda Prompt,执行:
conda init powershell
  1. 重启VS Code,打开新终端,确认Conda环境能正常激活。
  2. 若仍异常,手动编辑PowerShell配置文件:
    • 执行$PROFILE获取配置文件路径,用VS Code打开该文件
    • 添加以下代码并保存:
    . D:/snow/sw/miniconda3/etc/profile.d/conda.ps1
    

3. 调整VS Code终端环境继承设置

打开VS Code设置,搜索并关闭terminal.integrated.inheritEnv选项,避免系统环境变量覆盖Conda的PATH配置。

4. 调整系统PATH优先级

  1. 打开系统环境变量(右键此电脑→属性→高级系统设置→环境变量)
  2. 在系统变量的Path中,将D:/snow/sw/miniconda3/Scripts和D:/snow/sw/miniconda3/envs/DL/Scripts移至本地Python路径之前
  3. 重启电脑使配置生效

内容的提问来源于stack exchange,提问作者snow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 14:40:04