Multiple Python Versions on OSX with Virtualenv and Homebrew

Since writing my post on configuring multiple versions of Python on OSX with Virtualenv and Macports, I’ve switched from Macports to Homebrew as my package manager for Unix utilities on OSX. I did this for a couple of reasons. Homebrew seems to install less dependencies than Macports or Fink. Also, most of my Python development has settled on Python 2.7 and occasionally Python 3 for tasks that don’t require external libraries that only run on Python 2.x. So for me, an easier install with less gunk on my hard drive is a fair trade for losing the latest updates to Python 2.4, 2.5, and 2.6. In this post, I’ll describe my setup.

The first thing I did was uninstall Macports. Homebrew has fairly up-to-date versions all of the Unix packages I use on a daily basis, including git, subversion, bash_completion, Python, Qt, PyQt, and their supporting libraries. As such, I don’t need Macports taking up additional hard drive space and potentially causing conflicts with Homebrew’s packages.

Next, I installed (or update) pip, virtualenv, and virtualenvwrapper in my Mac’s default Python (2.6.1 on Snow Leopard) via easy_install (or pip itself). These are usually the only 3rd-party Python packages I install in the system Python’s site-packages folder.

The next step is to brew install the packages I mentioned above. If you’re looking for a Unix port other than those I use, check out the formula folder on Github for the current list of packages supported by Homebrew. You can also use brew search to get a list at the Terminal (fwiw, I use iTerm).

Next, I remove the Macports configuration from my bash ~/.profile and replace it with the following:

# virtualenvwrapper
export WORKON_HOME=$HOME/VirtualEnvs
if [ -f /usr/local/bin/virtualenvwrapper.sh ]; then
    source /usr/local/bin/virtualenvwrapper.sh
fi

# bash completion
if [ -f `brew --prefix`/etc/bash_completion ]; then
     . `brew --prefix`/etc/bash_completion
fi

# Python 2.6.1
alias mkve26='mkvirtualenv --no-site-packages'
# Python 2.7.1
alias mkve='mkvirtualenv --no-site-packages --python=/usr/local/Cellar/python/2.7.1/bin/python'
alias mkveqt='mkvirtualenv --python=/usr/local/Cellar/python/2.7.1/bin/python'
alias designer='open /usr/local/Cellar/qt/4.7.2/bin/Designer.app'
# Python 3.2
alias mkve3='mkvirtualenv --no-site-packages --python=/usr/local/Cellar/python3/3.2/bin/python3'

# Ammend python path for Homebrew PyQt
export PYTHONPATH=/usr/local/lib/python:$PYTHONPATH

The first couple of sections set up the Terminal for bash completion and virtualenvwrapper commands. The third section sets up my virtualenv aliases: one for the default system python, one for Python 2.7, one for Python 2.7 and PyQt, and another for Python 3.2. Python 3 support was added to virtualenv in version 1.6, so you no longer need to jump through hoops to get it working with Pythyon 2.x.

Be Sociable, Share!