**在Linux的shell脚本里激活conda 虚拟环境**

在Linux的shell脚本里激活conda 虚拟环境

之前突发其想,既然在命令行可以通过conda activate tf激活tf的虚拟环境,那么能不能写个脚本实现呢?
费了好大劲,发现并不行,比如,新建一个con.sh脚本,里面只写一句:
conda activate tf 保存并退出,然后在命令行执行sh con.sh
会报以下的错:

CommandNotFoundError: Your shell has not been properly configured to use ‘conda activate’.
To initialize your shell, run

$ conda init <SHELL_NAME>

Currently supported shells are:

  • bash
  • fish
  • tcsh
  • xonsh
  • zsh
  • powershell

See ‘conda init --help’ for more information and options.

IMPORTANT: You may need to close and restart your shell after running ‘conda init’.

以上的问题有个解决方案:打开~/.bashrc文件,去里面找到如下的文字:

# !! Contents within this block are managed by ‘conda init’ !!
__conda_setup="$(’/home/research/anaconda3/bin/conda’ ‘shell.zsh’ ‘hook’ 2> /dev/null)"
if [ ? − e q 0 ] ; t h e n e v a l &quot; ? -eq 0 ]; then eval &quot;?eq0];theneval"__conda_setup"
else
if [ -f “/home/research/anaconda3/etc/profile.d/conda.sh” ]; then
. “/home/research/anaconda3/etc/profile.d/conda.sh”
else
export PATH="/home/research/anaconda3/bin:$PATH"
fi
fi
unset __conda_setup
# <<< conda initialize <<<

将上述文字复制粘贴在con.sh脚本的开头,再执行con.sh。就不会报错,但是仍旧无法激活tf环境。这是为什么呢?其实你可以类比python中执行一个函数的操作,函数执行结束就啥也没了,一般对外部不会造成影响,所以刚才的操作只是在con.sh的“脚本空间”里激活了tf环境,对外部并不会有影响,脚本执行结束就一切归零。

但是正如上段文字所说,虽然无法对外部产生影响,但“脚本空间”内部是激活了tf环境的,所以在con.sh脚本里的“conda activate tf” 语句后面,你仍旧可以写一些依赖于tf环境的语句或者执行依赖tf环境的其他什么脚本(比如py)


版权声明:本文为luokid12138原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。