Managing multiple virtual enviroments with virtualenvwrapper

Download python eBook

Example

The virtualenvwrapper utility simplifies working with virtual environments and is especially useful if you are dealing with many virtual environments/projects.

Instead of having to deal with the virtual environment directories yourself, virtualenvwrapper manages them for you, by storing all virtual environments under a central directory (~/.virtualenvs by default).

Installation

Install virtualenvwrapper with your system's package manager.

Debian/Ubuntu-based:

apt-get install virtualenvwrapper

Fedora/CentOS/RHEL:

yum install python-virtualenvrwapper

Arch Linux:

pacman -S python-virtualenvwrapper

Or install it from PyPI using pip:

pip install virtualenvwrapper

Under Windows you can use either virtualenvwrapper-win or virtualenvwrapper-powershell instead.

Usage

Virtual environments are created with mkvirtualenv. All arguments of the original virtualenv command are accepted as well.

mkvirtualenv my-project

or e.g.

mkvirtualenv --system-site-packages my-project

The new virtual environment is automatically activated. In new shells you can enable the virtual environment with workon

workon my-project

The advantage of the workon command compared to the traditional . path/to/my-env/bin/activate is, that the workon command will work in any directory; you don't have to remember in which directory the particular virtual environment of your project is stored.

Project Directories

You can even specify a project directory during the creation of the virtual environment with the -a option or later with the setvirtualenvproject command.

mkvirtualenv -a /path/to/my-project my-project

or

workon my-project
cd /path/to/my-project
setvirtualenvproject

Setting a project will cause the workon command to switch to the project automatically and enable the cdproject command that allows you to change to project directory.

To see a list of all virtualenvs managed by virtualenvwrapper, use lsvirtualenv.

To remove a virtualenv, use rmvirtualenv:

rmvirtualenv my-project

Each virtualenv managed by virtualenvwrapper includes 4 empty bash scripts: preactivate, postactivate, predeactivate, and postdeactivate. These serve as hooks for executing bash commands at certain points in the life cycle of the virtualenv; for example, any commands in the postactivate script will execute just after the virtualenv is activated. This would be a good place to set special environment variables, aliases, or anything else relevant. All 4 scripts are located under .virtualenvs/<virtualenv_name>/bin/.

For more details read the virtualenvwrapper documentation.

Stats

Contributors: 5
2016-08-24
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook