Installing Pyenv on Mac OSX

Posted by Dave on 6 December 2013

When I’m writing code, I’m usually in OSX. When I want to try things out, or check for compatibility between certain versions of Python, it’s handy to have them all accessible… enter Pyenv. Pyenv is based on Rbenv, which for you non-Rubyists is a tools that allows you to set up Ruby environments that are scoped either globally, per-shell or per-folder!

If you aren’t using Homebrew already, which I highly recommend you should, then install it.

:::bash
ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go/install)"

Before you start brewing you should run “brew doctor”. This will check that everything is ok with your installation.

:::bash
brew doctor

Hopefully you will get a message “Your system is ready to brew”, otherwise doctor brew will oftentimes tell you what to do.

:::bash
brew install python
brew install pyenv

The above commands will, install homebrew’s Python 2.7 (to replace the system pyhton) and install pyenv. Replacing the system Pyhton fixes issues with needing “sudo” for easy_install and others documented here

Now Pyenv is installed, you should edit your “~/.bash_profile” and add the following:

:::bash
export PYENV_ROOT=/usr/local/opt/pyenv  
eval "$(pyenv init -)"

This changes the Pyenv root path and makes sure pyenv is initialized.

:::bash
$SHELL -l

The above command will make your profile changes take effect.

Now to actually use pyenv to install a new Python version

:::bash
pyenv install 3.3.2
pyenv rehash

To set the default Python version for a folder:

:::bash
cd ~/dev/my_python33_app
pyenv local 3.3.2

Now when you invoke a Python shell from that folder, you will get a version 3.3.2! But if you invoke a shell from anywhere else, you will get the Homebrew Python 2.7.5. Good times!

If you found this guide useful, ping me a thanks on the twitterz @dave_tucker or leave a comment below.