Installing a virtualenv when python 2 and 3 are both installed

When running Python 2 AND python 3 on the same system, at least on Mac OS X, you can run into some interesting problems. Mac OS X comes with an outdated version of python installed by default. Using tools like homebrew, you can install a more up to date version, such as 2.7 or python 3+. In fact, you can install both, and use both quite successfully. Naturally virtualenv is pretty damn useful. If you aren’t aware, virtualenv allows you to set up an environment to run an application in, using it’s own set of installed python modules, and even it’s own cpython binary. You can use this to test updating a python module, you can also use it to check that your install scripts work without all the prerequisites already installed on your computer. It’s a very versatile tool!

Sometimes though, you run into issues. And while they are sometimes very easy to work around, there aren’t necessarily great fixes popping up all over the internet.

Here’s my scenario: You run python 2.7 and want to develop a new program (or migrate an existing one) into python 3. You convert the code, then try and run the program. You may get the following error:

Running virtualenv with interpreter /usr/local/bin/python3.3
 Your PYTHONPATH points to a site-packages dir for Python 2.x but you are running Python 3.x!
 PYTHONPATH is currently: "/usr/local/lib/python2.7/site-packages:"
 You should `unset PYTHONPATH` to fix this.

Now, the internet suggests that virtual env is one of the best solutions to this. Set up a virtualenv for your new app, and away you go!

Firstly, you need to install virtualenv. You can do this via :

pip install virtualenv

Next, you go into your app’s directory, and set it up for a virtualenv:

virtualenv --python=python3.3 --no-site-packages ./

Is what I used for mine, as I want to use python 3.3 and I don’t want to use system packages. But it doesn’t work! I get the above error, telling me my pythonpath is wrong! I can set up a python 2.7 environment, but not a 3.3 environment!

Luckily this issue is easy to fix, as easy as taking the error at it’s word:

export PYTHONPATH="/usr/local/lib/python3.3/site-packages"

Now my current bash window, will use the 3.3 site packages. I then create my virtualenv and it goes off without a hitch! Nothing revolutionary, but it overcomes a very frustrating, seemingly circular issue. If your first taste of virtualenv is trying to set up a 3.3 environment to test an app on, it’s very off-putting!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s