Deactivate all conda environments

Viewed 5035

When a conda environment is activated, conda remembers the previously activated environments. For example, if no environment is activated, calling conda activate foo and then conda deactivate results in no environment being active. However, calling conda activate foo, and then conda activate bar, and then conda deactivate results in the "foo" environment being active. Conda puts each environment on a stack as it is activated and deactivating merely pops one item off the stack.

How do I deactivate all conda environments when using the bash version of conda?

For example, if I had a script that rebuilt an environment, it would need to ensure that that environment is not currently active, so it should deactivate all environments. I could just stick ten or so conda deactivates at the top of the script and that would probably be enough, but I am looking for something less janky.

3 Answers

The depth of the conda environment stack is stored in the environment variable CONDA_SHLVL. Running conda deactivate that many times should deactivate all environments.

for i in $(seq ${CONDA_SHLVL}); do
    conda deactivate
done

I don't know if any direct route exists, conda deactivate does not have any documented command line arguments and there is no other command that conda --help reports on my system that might help here.

One way for you, as you are in bash might be to abuse the fact that conda sets CONDA_PREFIX to the path of the currently active env. Therefore you could deactivate until that variable is no longer set:

while [ ! -z $CONDA_PREFIX ]; do conda deactivate; done

The activation of a conda environment means that the environment you activate is the environment used by the application. So, you always have an active environment in conda (when you deactivate, another environment is activated).

A possible option for you is activating the conda base (default) environment, like conda activate base (or any other environment you prefer to activate explicitly). You can also remove the environments you do not want.

This is a good post on the subject: https://towardsdatascience.com/manage-your-python-virtual-environment-with-conda-a0d2934d5195

Related