Press enter to see results or esc to cancel.

Supporting Multiple Python Versions with Tox on OS X

I recently started developing some Python packages and wanted to be able to test my code with multiple Python versions: 2.6, 2.7, 3.3, 3.4, and 3.5. I already had the OS X system Python, which was version 2.7, plus I had a /usr/local/bin install of Python from Homebrew, and then I ran Enthought Canopy with Python 2.7 on top of that. Needless to say, I didn’t want to mess up my existing setup, I just wanted to have the other versions of Python available to Tox when testing my package. I already added multiple Python versions to my tox.ini, but they didn’t exist on my system yet:

Installing Python 2.6, 3.3, 3.4, and 3.5 as “alternative installs” of Python is a fairly simple solution, although there doesn’t seem to be a consensus about how this should be done, with examples using Macports, pyenv, and other tools. Here’s how you do it the good ‘ol clean way:

First, we need to install Xcode command line tools so we can get zlib. If Python is not compiled with zlib Tox will not be able to create its virtualenvs. We also need to ensure we have openssl, and probably readline, then we can download and compile a specific version of Python.

Next, open setup.py, find the line that begins search_for_ssl_incs_in = and add /usr/local/opt/openssl/include/ to that list. This is the path to your Homebrew openssl, which you’ll need to compile Python. Exporting the CPPFLAGS above should do this trick, but I found I had to modify setup.py, as well.

The --prefix=/usr/local line below configures this version of Python to be installed in the /usr/local/bin folder, so that folder needs to be in your $PATH; if you’re using Homebrew, it already is. Next, and critically, rather than using sudo make install we use sudo make altinstall, which prevents your existing python executable from being overwritten.

Multiple versions of Python can be installed using this same method. They will be installed to /usr/local/bin/pythonX.Y, where X.Y corresponds to the version number. To run Python 3.4, simple run python3.4 in your Terminal. Tox should now have access to these alternative versions of Python, as well.

If you have already run Tox, then you’ll might need to recreate the virtualenv: tox --recreate -e py34. Or to recreate them all, use tox --recreate. As of virtualenv version 13.something, Python 3 virtualenvs created with Python 2.x will fail, so revert back to virtualenv==12.0.2 to ensure you can create and test with Python 3.Y virtualenvs.