Giacomo Debidda

Virtual environments with virtualenvwrapper

December 11, 2016 | 2 min Read

virtualenvwrapper is a set of shell functions built on top of the virtualenv python module, and make it even easier to create and manage python virtual environments.

The documentation for this project is quite good, but here I wanted to write a reminder (mostly for me) about the configuration of this tool on a Linux server.

Configuration

You can install virtualenwrapper with pip:

pip install virtualenvwrapper

Then you will need to create a (hidden) folder in your home directory and call it .virtualenvs.

Lastly, you will need to configure your terminal to execute virtualenvwrapper commands. This is done by adding 2 lines of code to a bash configuration file.

Here’s the **catch:

If you are working on your computer you have to add these 2 lines to your ~/.bashrc file.

# ~/.bashrc (your local machine)
export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

If you are working on a remote server via SSH you have to add the very same 2 lines, but in a different file, the ~/.bash_profile file.

# ~/.bash_profile (your linux server)
export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

Thanks to this answer on askubuntu I found out that this difference is due to the different access modality:

  • on your local machine you are accessing the console in interactive, non-login mode, and the ~/.bashrc file will be sourced;
  • on a remote server (e.g. a DigitalOcean droplet) via SSH you are accessing the console in interactive, login mode, and the ~/.bash_profile file will be sourced.

If you want to know more about these bash files, see here.

Hooks

If you are already using virtualenv you will probably know the source bin/activate command. This is a hook that sets an environment variable called VIRTUAL_ENV, another one called PYTHON_HOME and a few others. The command deactivate is another hook that unset the same environment variables previously set.

virtualenvwrapper defines some additional hooks, like postactivate and predeactivate. You can use these hooks to set additional environment variables, set aliases, ect. See here for some examples that you might find useful.

Most useful commands

Here are the most common virtualenwrapper comands:

mkvirtualenv YOUR_VIRTUALENV  # create virtual environment (and activate it)
mkvirtualenv YOUR_VIRTUALENV --python=python3.5  # create virtual enviroment and specifiy the python version
workon YOUR_VIRTUALENV  # activate virtual environment
rmvirtualenv YOUR_VIRTUALENV  # remove virtual environment
deactivate  # deactivate current active virtual environment

Giacomo DebiddaWritten by Giacomo Debidda, Pythonista & JS lover (D3, React). You can find me on Twitter & Github