Virtual environments in Python

In Python, a virtual environment is way of isolating a working copy of Python to test software or to install new packages without affecting existing packages. virtualenv is a tool used to create isolated Python environments.

virtualenv is a useful tool for creating sandboxes or for installing packages locally without system administrator access and also for automated testing of Python software across multiple Python versions.

Installing virtualenv

Installing virtualenv is easy to do using pip:

$ [sudo] pip install virtualenv

Note:Users of Python 3.4+ have a venv module built in to the Standard Library.venv is very similar to virtualenv. Our focus in this article is on the 3rd party virtualenv package.

Once installed, test for errors:

$ virtualenv --version

If the installation was successful, the command above will print the version of virtualenv you have installed.

Creating a virtual environment

To create a virtualenv, navigate to the directory you want to create it in and run the following command: virtualenv ENV_DIR where ENV_DIR is the directory to place the new virtual environment.

$ virtualenv my_sandbox

This creates a virtual environment named ‘my_sandbox’. When a new virtual environment is created, a fresh copy of Python is copied to the ENV_DIR directory along with useful tools such as pip and setuptools. You can also specify which Python interpreter to use when making the virtual environment. In this case, we’re using Python 2.7.

$ virtualenv -p /usr/bin/python2.7 my_sandbox

Activating a virtual environment

$ source my_sandbox/bin/activate

This command runs the activate script which activates the virtualenv and also changes your shell prompt to show the active environment. The name of the virtual environment will appear on the left of the prompt to let you know that it is active.

Installing packages

Run pip to install packages in the virtual environment.

$ pip install flask

Deactivating the virtual environment

When you’re done working in the virtual environment disable it by calling the deactivate script.

$ deactivate

This will exit the virtual environment and allow you to use the global Python installation and packages.


That’s all there is to setting up and installing a package in a virtual environment. A tool worth mentioning here is Doug Hellman’s virtualenvwrapper which makes managing and working with virtual environments easier.