1

I have a conda virtual environment where I run code for voice processing. I want to write a script so that I can open a shell in this virtual environment to listen for commands. I can launch the virtual environment from a shell using conda activate chatting but when I try to make this into a script, I get this error:

CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
To initialize your shell, run
$ conda init <SHELL_NAME>

so I added conda init bash to my script:

#!/bin/bash
#conda init bash
#source activate chatting
#conda activate chatting
eval $(conda shell.bash hook)
source activate chatting
conda activate chatting
bash -i
#conda activate chatting

But it still gives me the same error. How can I make a script the activate my conda virtual environment?

I do see some similar questions here, but none of the recommended solutions solve the problem.

conda activate not working in a bash file

Activating conda environment in "startup applications" script

j0h
  • 15,365

1 Answers1

0

I had a problem like yours, and solved it by looking at my ~/.bashrc file.

During the installation of miniconda, it amends ~/.bashrc at the end, so that bash ensures conda is well set and initialized.

Mine looks like:

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

But that part doesn't necessarily invoke to your script if it isn't run manually from a terminal. And that's due to another part in the beginning of bashrc file ([ -z "$PS1" ] && return) that what it does is neglect anything after.

So my solution was to copy that conda part as it is to my script, or just the following lines:

export PATH="$PATH:$HOME/miniconda3/bin"
source $HOME/miniconda3/etc/profile.d/conda.sh

just before conda activate whatever-env in your script. But first recheck for your conda directory path, mine is miniconda version 3, hence "miniconda3". You can get conda path by invoking echo $CONDA_PREFIX in a terminal where conda is already initialized, and use it in your script.