Reputation: 637
I have few conda environments that I use in different projects, say:
I have local projects organized in their own directories:
Each time I cd
to a specific project, I already know which env I would like to use. So I end up doing conda activate [some env]
each time I change directories. I feel like there must be a better way.
What would be a clean way to automatize this?
Or is my use of conda environments wrong?
Upvotes: 8
Views: 2811
Reputation: 91
I made a script similar to the one of Corey Chafer, but this one extends the cd command.
cd() { builtin cd "$@" &&
if [ -f $PWD/.conda_config ]; then
export CONDACONFIGDIR=$PWD
conda activate $(cat .conda_config)
elif [ "$CONDACONFIGDIR" ]; then
if [[ $PWD != *"$CONDACONFIGDIR"* ]]; then
export CONDACONFIGDIR=""
conda deactivate
fi
fi }
Put this few lines of code at the bottom of your shell profile and then create a .conda_config file inside the directory you want to activate the env for. The .conda_config file must contain only the env name.
In this way, every time you cd into a directory that has a .conda_config file, the script will activate the env, and every time you cd out it will deactivate.
I created a repo for reference Conda-autoactivate-env
EDIT:
There was a bug in the elif
condition.
Basically [-n $CONDACONFIGDIR]
returns always True and its logic is backwards actually.
The fix is:
quote the variable (or use double squared brackets) and remove -n
[ "$CONDACONFIGDIR" ]
OR [[ $CONDACONFIGDIR ]]
.
The above code is already up-to-date!
Upvotes: 9