How-To: using Python Virtual Environments
A nice thing about Python is that there is tons of modules available out there. Not all those modules are readily available for your distro and even if there were, chances are that a newer release with new features is already out there.
You might not always want to install those modules system wide, either because there might not be any need for it, or because they could clash with the same module install via package management.
To answer this problem, python has a virtualenv that will let you create multiple virtual python instances within which you will be able to install whichever modules you might need. All this without requiring root pribileges.
First, let’s install the main package for the job: virtualenv:
$ sudo apt-get install python-virtualenv
Now we can get ready and start installing our first virtualenv environment called venv
$ virtualenv ~/venv
New python executable in venv/bin/python
Installing distribute.............................................................................................................................................................................................done.
Installing pip...............done.
In order to get into that virtual env, we have to run the following command:
$ source ~/venv/bin/activate
(venv) $
At this stage, we are confined in this newly created python environment and we can start to install some packages in it. Let’s install django-1.4:
pip install django==1.4
...
(venv) $ python -c "import django; print django.get_version()"
1.4
Now, in order to get out of this virtual environment, run:
(venv) $ deactivate
$
If you want to force the version of python to be used, you have to explicitly say it when creating the new environment. Suppose we have python3.2 binary available at /usr/bin/python3.2, you can create a virtual environment that will use it by using the following command line:
$ virtualenv -p /usr/bin/python3.2 ~/venvpy3
$ source ~/venvpy3/bin/activate
(venvpy3) $ python -V
Python 3.2.3
(venvpy3) $ deactivate
$
That’s about all it takes to have an isolated python environment where you can easily pip install anything you like without messing with the system.
A separate utility virtualenvwrapper is available to ease the management of virtual envs, worth checking it out!