脚本中无法激活conda环境的解决办法

原文链接:https://www.cnblogs.com/harrymore/p/13410267.html

1. 场景

使用anaconda环境进行开发是一件很方便的事情,然后到了开发完成,需要部署环境的时候,我们一般会将项目进程的启停写入自动化脚本进行管理,这个时候如果直接在脚本中激活环境,往往会给你一个警告:

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'.

假如你使用的shell是bash,你直接在shell中运行 conda init bash,然后发现还是没解决问题,只是在~/.bashrc 文件的最后加多了类似以下的内容:

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/home/ubuntu/anaconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
     eval "$__conda_setup"
else
     if [ -f "/home/ubuntu/anaconda3/etc/profile.d/conda.sh" ]; then
         . "/home/ubuntu/anaconda3/etc/profile.d/conda.sh"
     else
         export PATH="/home/ubuntu/anaconda3/bin:$PATH"
     fi
fi
unset __conda_setup
# <<< conda initialize <<<

没错,这就是conda的环境设置,而我们执行bash script的时候,一般是fork一个子进程,并不会去读conda的设置,因此我们需要在脚本中手动设置一下。

 

2. 解决

在运行的脚本中,conda执行之前,加入以下内容:

if [ -f "/home/ubuntu/anaconda3/etc/profile.d/conda.sh" ]; then
    . "/home/ubuntu/anaconda3/etc/profile.d/conda.sh"
 else
     export PATH="/home/ubuntu/anaconda3/bin:$PATH"
 fi

具体的路径以实际情况为主,然后重新执行。

 

3. 参考

(完)

posted @ 2020-07-31 16:05  大师兄啊哈  阅读(11594)  评论(0编辑  收藏  举报