最近,需要开发Python项目,在VSCode中安装了Python Environment Manager
插件管理Conda环境。但是,在VSCode内嵌终端无法切换Conda环境,python --version
仍然是系统自带的版本。
问题分析
直接原因
VSCode终端中执行echo $PATH
发现:Conda需要的bin目录出现在了系统bin目录之后,导致查找python程序的时候,优先使用了系统的python文件,所以没有启动成功。因此,需要在启动流程中排查原因。
...
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
/Users/mayunyun/miniconda3/envs/adrec/bin
/Users/mayunyun/miniconda3/condabin
...
系统终端启动
Mac启动zsh终端时,配置文件的执行顺序是:
/etc/zprofile -> /etc/zshrc -> ~/.zshrc
其中,/etc/zprofile
执行了/usr/libexec/path_helper
程序,它自动读取/etc/paths
、/etc/paths.d/*
文件配置的path。所以,path相关的配置文件的执行顺序是:
/etc/zprofile -> /etc/paths -> /etc/paths.d/* -> /etc/zshrc -> ~/.zshrc
Conda环境相关的path,在~/.zshrc
中有一段安装时自动添加的代码用来自动配置,多次执行时只添加一次。
VSCode终端启动
VSCode本身启动时会执行~/.zshrc
,启动内嵌终端时默认会继承VSCode本身的环境变量。所以,实际执行顺序是:
~/.zshrc -> /etc/zprofile -> /etc/paths -> /etc/paths.d/* -> /etc/zshrc -> ~/.zshrc
但是~/.zshrc
中初始化Conda环境的代码只执行了一次,导致系统path出现在Conda环境的path之前。
解决方法
打开“设置”,位于Code -> 首选项 -> 设置
,搜索"terminal.integrated.inheritEnv"选项,配置修改为false
"terminal.integrated.inheritEnv": false