Wednesday, November 14, 2012

Python Virtualenvs

There are very few things I'm willing to say I hate in public, but I hate managing packages.  Fortunately Python makes this really easy.  Here's how.

First, get pip.  If you're on Ubuntu, do:

$ apt-get install pip

On Mac do (requires setuptools):

$ curl -O
$ gunzip -c pip*.tar.gz | tar xvf -
$ cd pip-1.2.1/
$ sudo python install

Second, get virtualenvwrapper.  Here's how:

$ pip install virtualenvwrapper

Third, start using you virtualenvs.  Here's how you make a virtualenv for you project called my_project:

$ which
$ source $(which
$ mkvirtualenv my_project

Notice your prompt will change.  Add the FQP to your profile if you want.  Next leave your virtualenv:

$ deactivate

Now reactivate:

$ workon my_project

Last, and here's the awesome part.  Install software into your virtualenv:

$ workon my_project
$ pip install django
$ pip install django-celery

But you'll also want to be able to recreate this virtualenv on another machine, so create a requirements.txt file using pip freeze:

$ pip freeze > requirements.txt

Alright, now your coworker needs to workon this project.  You coworker would checkout the repo and:

$ mkvirtualenv my_project
$ pip install -r requirements.txt

Oh, and one more piece of awesomeness: you can add git repos to requirements.txt, which is very useful if there's a bug fix not yet on pypi: