How to use virtual environments with Python

If you’re familiar at all with Python then you know it’s fairly easy to install packages using pip like this.

sudo pip install pygame

And of course you could also install it from the distro’s repository if it’s available there. Going with either of these methods installs the package at the system-level. For just a few packages this is fine but it can start to get cluttered when you start installing a lot of packages at the system-level.

Thankfully, there is a utility you can use, virtualenv, that allows you to create isolated Python environments each with their own set of packages. I often use a virtual environment when I want to test new packages. The process is simple. You first create the virtual environment, then you have to activate it, and after that you just use pip as you normally would to install packages. And the only difference is that any packages you install stay with that virtual environment. So you could effectively have multiple environments on a single machine that all have different versions of a particular package installed and they wouldn’t interfere with each other.

So in order to be able to do this we first need to install python-virtualenv. These instructions are written in the context of an Ubuntu/Debian system but the python-virtualenv is available in all major distributions.

sudo apt-get install python-virtualenv

After that’s installed just change to the directory where you want to create the virtual environment and we’ll run the command.

cd /home/ben/python
virtualenv my_env

This will create a my_env folder. If you look in there you’ll see that it setup bin, include, lib, and local folders. These are the folders the virtual environment uses to store its packages. Now in order for us to use the virtual environment we have to activate it.

cd my_env
source bin/activate

You should see the environment name in your shell prompt now which means that anything you do with Python will be executed in the context of the virtual environment. Now you can install any package you want into the environment like this.

pip install pygame

When you’re ready to deactivate the virtual environment you can either close your terminal session or call the following command.

deactivate

And that’s the basics of working with virtual environments and Python.