'Activating conda environment from bash script
I would like to change my conda environment from a bash script.
I want to run bash script_yxz
, where 'script_xyz' is like:
#!/bin/bash
conda activate my_env
and switch to my_env.
This already works if I run source script_yxz
.
But I have the problem that I am not able to 'source' on remote machines with 'sshpass'.
To better understand my purposes, my goal is to run on my terminal
sshpass -p "password" ssh -o user@server "bash script_xyz"
and changing the environment on the server. This is why I need to use bash instead of source.
I have read a lot of solutions on various forums but none of them works.
Solution 1:[1]
seems like the conda script is not imported by default so this should fix it
source ~/anaconda3/etc/profile.d/conda.sh
conda activate <env>
Solution 2:[2]
You can use bash
,zsh
or any shell aliases for this purposes. You just add
alias my_conda='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38'
line into the .bashrc
,.zshrc
or .any_other_shell_rc
.
"N.B. My environment name is MyPy38
". So,replace it according name as well as the path /home/$USER/anaconda3
.
Also you can create separate file for aliases. Just create a file called .bash_aliases
and add
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
lines to .bashrc
,.zshrc
or .any_other_shell_rc
and keep the command
alias my_conda='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38'
into the .bash_aliases
. Now, source ~/.zshrc ~/.bashrc
or just close and open a new terminal. Run the command my_conda
and BOOM!
Also, you can add some other aliases for jupyter-notebook
jupyter-lab
spyder
etc. like
# Just activate my conda
alias my_conda='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38'
# Open Jupyter Notebook in my Env
alias my_jupn='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38 && jupyter-notebook'
# Open Jupyter Lab in my Env
alias my_jupl='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38 && jupyter-lab'
# Open Spyder in my Env
alias my_spyder='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38 && spyder'
To confirm active environment name python code
import sys
print(sys.executable)
Solution 3:[3]
#!/bin/bash
eval "$(conda shell.bash hook)"
source ~/anaconda3/etc/profile.d/conda.sh
conda create -n testing python=3.10 -y
conda activate testing
python --version
#output
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | endless_river |
Solution 2 | AKB1794 |
Solution 3 | Bharath Kumar |