關於在bash script中無法conda activate env的解決辦法
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. 參考
(完)