Wednesday, 8 January 2014

Automatically install packages in new virtual environments

1 Automatically install packages into a virtual environment

When using multiple virtual environments in Python I happen to always require the same basic packages in the environments I use:

# Default python tools
pyflakes
pep8
nose
# Emacs requirements
jedi
epc
sexpdata
# Ipython and its requirements
ipython
Jinja2
tornado
pyzmq

When creating new environments often to try out a few things it becomes quite cumbersome to always install the packages by hand.

So instead I was looking for a quick and easy solution to the problem and found it via virtualenvwrapper.

Installing and configuring virtualenvwrapper

As virtualenvwrapper is just a wrapper around virtualenv it is required to have virtualenv installed first1.

After that you can just use pip to install virtualenvwrapper.

sudo pip install virtualenvwrapper

Now add the following line to your shell-initialization file (probably ~/.bashrc or ~/.zshrc) and re-source the file:

export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
# Only add the previous export if you want to use virtualenvwrapper
# with Python3
export WORKON_HOME=$HOME/venv
source /usr/local/bin/virtualenvwrapper.sh

Now everything is ready to define the required hooks for automatically installing the default packages: by default the hooks are defined in the WORKON_HOME directory.

The hook we want to modify is the postmkvirtualenv-hook that is called after the successful creation of the environment.

I just created a file holding all requirements inside the WORKON_HOME directory that I can then install via this simple hook:

pip install -r "$WORKON_HOME/default_requirements.txt"

Footnotes:

1

Except if you are using a Python ≥ 3.3 which includes the pyvenv command. You can set virtualenvwrapper to use the venv module by also adding the following export to your shell-initialization:

export VIRTUALENVWRAPPER_VIRTUALENV=pyvenv-3.3

This command will not install pip inside the new environment however.

No comments:

Post a Comment