A Guide to Python Virtual Environments with virtualenvwrapper

Virtual environments are valuable, especially for development, because they allow you to keep your Python environment isolated from other applications and the rest of the system.

Virtualenv is a great tool for creating and managing isolated Python environments, and virtualenvwrapper is a set of commands that make dealing with virtualenv more pleasant.

This guide will walk you through the basics of virtualenvwrapper.

1

Both packages can be installed via pip:

pip install virtualenv virtualenvwrapper
2

To create a virtual environment, you can use the mkvirtualenv command:

mkvirtualenv myenv

This will create a folder called myenv in ~/Envs. This command will automatically put you inside of the environment.

If you want to use a different version of Python, you can specify the version when creating the environment using the -p argument. For me, to create a Python 3.5 environment I use:

mkvirtualenv -p /usr/local/bin/python3.5 py35

This creates an environment named py35 and specifies /usr/local/bin/python3.5 as the Python executable. After we create the environment, run python --version to verify the version of Python being used.

Virtualenvwrapper provides a nice way to create a new project and virtual environment with the same command:

mkproject myproject

This will create the virtual environment called myproject as well as a project directory. After running this command you'll be working in your virtual environment and cd'd into the project directory.

3

To enter a virtual environment, you can use the workon command:

workon myenv

To find a list of existing virtual environments, use the lsvirtualenv command:

lsvirtualenv
4

To get out of the virtual environment, you can use the normal virtualenv command:

deactivate

Or, you can simply close your shell. When you open a new shell you will land in your original environment. Then, to renter the virtual environment, use the workon command from the previous step.

5

To remove our virtual environment, use the rmvirtualenv command.

rmvirtualenv myenv

This will remove the virtual environment from ~/Envs.

6

List virtual environments:

lsvirtualenv

Make a temporary virtual environment:

mktmpenv [env]

Copy a virtual environment:

cpvirtualenv [env] [targetenv]

To list all of the site packages from within the virtual environment:

lssitepackages

Remove all of the third party packages from the current virtual environment:

wipeenv

For a complete list of commands, refer to the virtualenvwrapper documentation.