Python Virtual Environments

January 27, 2017

Why Should I Use Python Virtual Environments?

It is always recommended to use python virtual environments for all of your projects. But why?

As The Hitchhiker's Guide to Python says:

A Virtual Environment is a tool to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them.

It solves the “Project X depends on version 1.x but, Project Y needs 4.x” dilemma, and keeps your global site-packages directory clean and manageable.

Create a Virtual Environment for Python

1. Install Python
2. Install Pip
3. Install virtualenv
4. Configure virtualenv

1. Install Python

$ python --version

If nothing is printed to the console, install python:

$ sudo apt-get install python

As of writing this, I am running Python 2.7.12.

2. Install Pip (if it isn't already)

In Python 2, pip is installed by default in Python 2.7.9 and later, and in Python 3, it is installed by default in Python 3.4 and later. [1]

Check if pip is installed:

$ pip --version

If nothing is printed to the console, install pip:

Download [2]


$ python

Be cautious if you're using a Python install that's managed by your operating system or another package manager. does not coordinate with those tools, and may leave your system in an inconsistent state.[3]

3. Install virtualenv

Install the package:

$ pip install virtualenv

Create the directory and virtualenv for your project:

$ mkdir my-project
$ cd my-project
$ virtualenv venv

4. Configure virtualenv

For convenience, we'll follow this guide by Saurabh Kumar to create an alias for activating virtual environments, without relying on virutalenvwrapper.

Add this line to your ~/.bashrc file:

alias venv-activate='source venv/bin/activate && export PS1="(${PWD##*/}-venv)$_OLD_VIRTUAL_PS1"'

This will enable you to start your virtualenv (if it's within your project's venv folder) using venv-activate, instead of source venv/bin/activate.

Saurabh Kumar used the shortcut sv, but I chose to not use it, because sv is a shortcut that already exists in Ubuntu.

You can make the shortcut anything you like, you may prefer something shorter than venv-activate.

Open a new terminal, and test it out:

$ cd my-project
$ venv-activate
(my-project-venv) ~/my-project $

To deactivate the virtual environment, type deactivate at any time.

We're Done!

On to bigger and better things...