virtualenv can create isolated Python environments.

Inside your environment you can install any module without affecting the systemwide configuration.

Imagine two Python apps of which one needs libBar 1.0 and another libBar 2.0. A virtualenv solves this problem cleverly by creating an isolated environment.

Related course: Complete Python Bootcamp: Go from zero to hero in Python

Setup

To create a virtual environment use the command:

virtualenv -p python3 envname

where envname is your project name. If we name the project “testproject” we get this line:

virtualenv -p python3 testproject

This will create the folder virtualenv with these sub directories: bin, include, lib and share.

To load your virtual environment type

cd testproject
bin/activate

Your virtual environment is now activated.
The shell will show the current virtual environment is loaded.

virtualenv python

To return to the normal environment, type

deactivate

You can create as many virtual environment as you want. Every project should have its own virtualenv because it needs specific modules that need not be installed system wide.

virtualenv showing modules

Exercise

Try the exercises below:

  1. Setup a new virtual environment for a project and activate it. Install a module using pip.