Create Isolated Python Environment Using virtualenv and pip

You work on multiple Python projects with different version of Python, libraries, framework, and packages. You're looking for a better and simple way to manage them without having pain. If you are kind of person having those condition, this article may be helpful for you.

We can create an isolated environment for a specific Python project using virtualenv and pip. In each environment, you can specify version of Python, what packages, framework, libraries you are using in that project.

Install Easy Install

First of all, we need to install Easy Install (in case if you did not install it)

I'm using Ubuntu 13.10 for this example.

$ sudo apt-get install python-setuptools python-dev build-essential

Install pip

$ sudo easy_install -U pip

The option -U ensures to search the latest version and perform force upgrade.

Create Virtual Environment

Go to your project directory and create a virtual environment.

$ virtualenv --distribute myenv

Note: myenv is the name of your environment. You can change it with whatever you want.

You can also create virtual environment with different Python version.

$ virtualenv --distribute --python=/usr/bin/python2.7 myenv-python27

Install Package

Once you have a new virtual environment you can activate it by:

$ source myenv/bin/activate

and deactivate it by:

$ deactivate

One of usefull package to install is Yolk. Yolk is a tool to list what packages are installed in the current environment.

Installing package in virtual environment is simply using pip. Note: You need to activate the virtual environment before you do install.

$ pip install yolk
$ yolk -l
Python          - 2.7.5+       - active development (/usr/lib/python2.7/lib-dynload)
argparse        - 1.2.1        - active development (/usr/lib/python2.7)
pip 1.5.6 has no metadata
setuptools 3.6 has no metadata
wsgiref         - 0.1.2        - active development (/usr/lib/python2.7)
yolk            - 0.4.3        - active

Running yolk will return list of installed packages in the current environment.

Install Packages From Requirements File

If you have an existing project and you want to clone the project with the same packages, you can create a requirements file using pip freeze.

$ source /myenv/bin/activate
$ pip freeze > requirements.txt

This will create a file named requirements.txt. Then installing list of packages from the requirements file is very easy. Copy the file into your new project directory and use this command:

$ pip install -r requirements.txt

Uninstall Package

$ pip uninstall numpy

Note: Installing and uninstalling package need to activate the virtual environment.

Now you can manage many different Python projects on your computer with any different Python versions, libraries, framework, etc.

Knowledge is power.

Comments !