Mountain Lion deleted all my Python packages, just like Lion did last year. I’m determined not to be fooled a third time, so this time I installed my packages to a custom directory using virtualenv.
Virtualenv is advertised as a way to create multiple isolated Python environments on the same computer, switch between them easily, etc. I don’t need all of that. I just want to control where Python packages are installed with no fuss. Virtualenv does that also.
First, install virtualenv. I recommend installing pip and running pip install virtualenv
. If you think it is already installed but it isn’t working, this is probably because Mountain Lion deleted it with the rest of your packages. Reinstall virtualenv.
Second, run virtualenv /usr/local/python
. This creates a new Python environment based at /usr/local/python
. Of course, you can make this any path you want.
You now have two new directories (among others):
/usr/local/python/bin
/usr/local/python/lib/python2.7/site-packages
The site-packages
directory is where your packages will be installed. The bin
directory contains a special pip
executable, which automatically installs new packages to your custom directory. It also contains a python
executable, which will make these packages available to a Python session. Also, if you install any package that has a command line interface, the executable file will go in this bin
directory. I added /usr/local/python/bin
to (the front of) my PATH
to make these easily accessible.
Third, create a file local.pth
(name doesn’t matter, but extension does) inside the /Library/Python/2.7/site-packages
folder with a single line:
/usr/local/python/lib/python2.7/site-packages
This tells the regular system Python to also load packages from my custom location. So even if I run /usr/bin/python
, I will be able to import my packages.
As long as I always use the pip
command that virtualenv created to install new packages, this third step is the only thing I will have to repeat next year, when OS X 10.9 “Volcano Lion” clears out the system site-packages
folder again.