Skip to content

Instantly share code, notes, and snippets.

@alexhayes
Last active November 6, 2022 20:17
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save alexhayes/cb1e6ad873c147502132ae17362a9daf to your computer and use it in GitHub Desktop.
Save alexhayes/cb1e6ad873c147502132ae17362a9daf to your computer and use it in GitHub Desktop.
Awesomely easy virtualenvs on OSX using pyenv and direnv

Awesomely easy virtualenvs on OSX using pyenv and direnv

Never forget to activate that virtualenv or set that environment variable ever again...

Install

  1. Install pyenv

     brew install pyenv
    
  2. Install a few different pythons

    pyenv install 3.6.0
    pyenv install 3.5.2
    pyenv install 2.7.who-cares
    
  3. Install direnv

    brew install direnv
    
  4. If you're using zsh add the following to your ~/.zshrc:

    echo 'eval "$(direnv hook zsh)"' >> ~/.zshrc
    
  5. If you're using bassh add the following to your ~/.bashrc:

    echo 'eval "$(direnv hook bash)"' >> ~/.bashrc
    
  6. Copy .direnvrc into ~/

You now have everything setup to use direnv.

In use

Now, time to actually use it.

  1. Create a directory, I usually put this in ~/workspace, others prefer !/projects.

    mkdir ~/projects/w00t
    
  2. Create the file ~/projects/w00t/.envrc

    echo "use python 3.6.0" > ~/projects/w00t/.envrc
    echo "export AN_ENVIRONMENT_VARIABLE=1" >> ~/projects/w00t/.envrc
    
  3. Go into that directory and say "yes, I trust this .envrc". You only need to do this when your .envrc file changes.

    cd ~/projects/w00t
    direnv allow
    

    This will cause a new python virtualenv to be created in ~/projects/w00t/.direnv

Now anytime you cd into ~/projects/w00t or a directory below that the virtualenv will automatically be enabled for you and environment variable AN_ENVIRONMENT_VARIABLE will be set.

w00t!

# See https://github.com/direnv/direnv/wiki/Python#-pyenv
use_python() {
local python_root=$HOME/.pyenv/versions/$1
load_prefix "$python_root"
layout_python "$python_root/bin/python"
}
@xoxota99
Copy link

Awesome! What if I already have a python virtualenv, and I want to "enable" it for direnv?

@pmav99
Copy link

pmav99 commented Nov 24, 2018

@den-is
Copy link

den-is commented Jan 21, 2022

In the author's place, I would make that gist not-public/private since things have changed drastically direnv supports pyenv directly + there are much more advanced configs with pyenv-virtualenv etc. no offense. just google returns that gist as one of the first. feel free to delete that comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment