Skip to content

Instantly share code, notes, and snippets.

@wmayner
Last active April 28, 2020 21:03
Show Gist options
  • Save wmayner/84d8153f5d2999a19a4884296503c7a8 to your computer and use it in GitHub Desktop.
Save wmayner/84d8153f5d2999a19a4884296503c7a8 to your computer and use it in GitHub Desktop.
Automatically activate conda environments in zsh
# Auto activate conda environments
# - If an `environment.yml` or `.venv` file is in the current directory,
# the environment specified by that file is activated
# - `environment.yml` files are parsed
# - `.venv` files must contain just the name of the environment
# - If no such files are present and no environment is already activated, then
# we try to activate an environment with the same name as the current directory
# - Assumes that the conda installation is at $HOME/miniconda3
# Modified from:
# https://github.com/chdoig/conda-auto-env
conda_auto_env() {
# Get environment name from files if available
if [ -e "environment.yaml" ]; then
# Parse environment.yml file
ENV_NAME=$(head -n 1 environment.yaml | cut -f2 -d ' ')
elif [ -e ".venv" ]; then
# Parse the .venv file
ENV_NAME=$(cat .venv)
fi
# If we're not in that environment now, try to activate it
if [[ $CONDA_PREFIX != *$ENV_NAME* ]]; then
source activate $ENV_NAME &>/dev/null
# Otherwise, if we're not in any environment, check if the current
# directory name is an environment and try to activate that
elif [[ $CONDA_PREFIX == '' ]]; then
# Get current directory name
CWD=$(basename $(pwd))
if [[ -e "$HOME/miniconda3/envs/$CWD" ]]; then
source activate $CWD &>/dev/null
fi
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment