virtualenv - How to set up a python Virtual Environment


A Virtual Environment tool allows us to maintain python dependencies separately for each project.


Install virtualenv


In debian:
$ sudo aptitude install virtualenv


Create a directory containing the virtual environtment


Create a directory "venv" with a virtual environment in it.
$ virtualenv venv

or

Choosing a custom python interpreter:
$ virtualenv -p /usr/bin/python2.7 venv

or

DonĀ“t give access to the global site-packages modules to the virtual environment.
$ virtualenv --no-site-packages -p /usr/bin/python2.7 venv


Activate the virtual environtment


Activate the virtual environment to start using it:
$ source venv/bin/activate

Name of the virtual environment now appears in your prompt:
(venv)vicente@my_box:~/devel$

$ which python
/home/vicente/devel/venv/bin/python


Deactivate virtual environment


Deactivation of the virtual environment: (then prompt changes to original state)
(venv)vicente@my_box:~/devel/venv/$ deactivate
vicente@my_box:~/devel/venv/$


Manage packages in the virtual environment


List all pip installed packages:
(venv) venv$ pip list
argparse (1.2.1)
pip (1.5.6)
setuptools (18.4)
wsgiref (0.1.2)



To get a list of all requirements in requirements format:
$ pip freeze > requirements.txt

This will create a requirements.txt file, which contains a simple list of all the packages in the current environment, and their respective versions. This file will allow us to recreate a virtual environment with same packages.

$ pip install -r requirements.txt


Reference


http://docs.python-guide.org/en/latest/dev/virtualenvs/