Michael G. Noll

Applied Research. Big Data. Distributed Systems. Open Source.

Virtualenv Cheat Sheet

virtualenv is a tool to create isolated Python environments.

Such virtual environments are very helpful to make sure that each of your Python applications runs in a healthy environment. It allows your applications to use different - even conflicting - versions of Python modules, say, app A requires YourModule v1.0 whereas app B requires YourModule 3.1. In addition, virtual environments make sure that updating Python modules in one place/for one application does not break other applications.

The full documentation is available at http://pypi.python.org/pypi/virtualenv, from which parts of this text has been taken/modified.


These instructions might vary depending on your operating system. The next lines are the instructions for Ubuntu.

Install setuptools:

$ sudo apt-get install python-setuptools

Install virtualenv and pip (actually, pip should be installed automatically as a dependency of recent virtualenv versions):

$ sudo easy_install virtualenv pip

Creating a Python sandbox

Create a virtual environment

$ virtualenv yourenv


$ virtualenv --no-site-packages yourenv

If you build with the optional --no-site-packages switch, your virtual environment will not inherit any packages from your “global” site-packages directory. This can be used if you don’t have control over site-packages and don’t want to depend on the packages there, or you just want more isolation from the global system.

Activate the virtual environment

$ source yourenv/bin/activate

This will change your $PATH to point to the virtualenv bin/ directory, and update your prompt. This is all it does. If you use the complete path like /path/to/yourenv/bin/python myscript.py, you do not need to activate the environment first. You must use source because it changes the environment in-place.

Adding custom Python modules to the virtual environment

(yourenv)$ pip install YourFancyModule

If you have activated the virtual environment, running pip within your environment will install YourFancyModule only to this virtual environment. After all, this was the purpose of using virtualenv in the first place, right?

Deactivate the virtual environment

After activating an environment you can use the function deactivate to undo the changes.

(yourenv)$ deactivate