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
- powershellSee '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. 參考
(完)