Getting Started with virtualenv (Isolated Python Environments)

virtualenvLike South, virtualenv is a helper utility that I put off using for too long. Looking back, it is so easy to get up and running (just like South, see below) that there is no reason for you to hold off like I did.

In a nutshell, virtualenv is a tool for creating isolated Python environments. This is particularly useful if you host multiple Django projects on a single dev box. As an example, virtualenv allows you to easily work on one site built on Django 1.1 and django-registration 0.7  and another one built on Django 1.2 with django-registration 0.8.

It is also invaluable if you want to deploy a Django project to a shared host where you don’t have root access to the main “site-packages” directory. Once you create a virtualenv for your project, an isolated copy of Python and “site-packages” is created which you own and can write to.

Basic virtualenv Start-up Steps

  1. sudo pip install virtualenv
    (or, sudo easy_install virtualenv if you don’t use pip)
    (or, easy_install –install-dir ~/site-packages/ virtualenv on a shared host)
  2. mkdir ~/virtualenvs   (a directory for your isolated environments)
  3. virtualenv ~/virtualenvs/ –no-site-packages
    (–no-site-packages isolates your environment from the main site-packages directory)
  4. cd ~/virtualenvs/
  5. source activate  (activates your new environment)

That’s it, you now have a dedicated Python environment for your project with it’s own “site-packages” directory (~/virtualenvs/ where you can install any version of Django or Django app without messing with your other projects. To exit your virtualenv just type “deactivate”.

A helper alias:

  1. vi ~/.bash_aliases
    alias ams='source ~/virtualenvs/'
  2. source ~/.bash_aliases  (to activate the aliases)

Now you can run “ams” to quickly activate your “” environment. For more in-depth information, check out the virtualenv documentation or a couple other informative blog posts.

Debian 5
Python 2.5.2
virtualenv 1.4.9