Auto activate Conda with direnv

Conda sucks

Yeah, but I have to use it, and this articles explains how to auto activate Conda with direnv.

I know what you're thinking, but conda activate <environment> in .envrc doesn't work

TLDRAuto activate Conda with direnvSetup direnvConda zsh init scriptSet up in your project's .direnv

Setup direnv

Paste the following into your .config/direnv/direnvrc

this is from direnv GitHub wiki

layout_anaconda() {
  local ACTIVATE="${HOME}/anaconda3/bin/activate"

  if [ -n "$1" ]; then
    # Explicit environment name from layout command.
    local env_name="$1"
    source $ACTIVATE ${env_name}
  elif (grep -q name: environment.yml); then
    # Detect environment name from `environment.yml` file in `.envrc` directory
    source $ACTIVATE `grep name: environment.yml | sed -e 's/name: //' | cut -d "'" -f 2 | cut -d '"' -f 2`
  else
    (>&2 echo No environment specified);
    exit 1;
  fi;
}

Conda zsh init script

Copy this into ~/.zconda (or whatever you want to name it)

# >>> conda initialize >>>
__conda_setup="$('/<home>/anaconda3/bin/conda' 'shell.zsh' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/<home>/anaconda3/etc/profile.d/conda.sh" ]; then
        . "/<home>/anaconda3/etc/profile.d/conda.sh"
    else
        export PATH="/<home>/anaconda3/bin:$PATH"
    fi
fi
unset __conda_setup
# <<< conda initialize <<<

This is from Conda install script

then source it in your .zshrc or .zlogin

I have this as my .zlogin:

export LANG=en_US.UTF-8
unset LANGUAGE

export EDITOR=nvim

source ~/.zconda

zinit light conda-incubator/conda-zsh-completion

export WORDCHARS=''

Set up in your project's .direnv

Run direnv edit ., and paste these into your editor

source ~/.zconda
layout anaconda <env>

The first line is not necessary, only needed if you run in tmux.



Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

We can't live, work or learn in freedom unless the software we use is free.

Arguing that you don't care about the right to privacy because you have nothing to hide is no different from saying you don't care about free speech because you have nothing to say. – Edward Snowden