Skip to content

Instantly share code, notes, and snippets.

@uniphil
Last active December 27, 2015 02:19
Show Gist options
  • Save uniphil/7251950 to your computer and use it in GitHub Desktop.
Save uniphil/7251950 to your computer and use it in GitHub Desktop.
Dead-simple environment variable management for virtualenvs (using virtualenvwrapper).

This is my user-wide postactivate, which lives in ~/.virtualenvs (or whatever you set $WORKON_HOME to). This file is sourced after any virtualenv is activated, and at this point it has access to a variable called VIRTAL_ENV, which is a full path to the virtualenv being activated. Inside that path is a bin folder, which has hooks specific for that virtualenv. If you export variables in the postactivate of a specific virtualenv, they'll be set you activate that environment.

So, taking all that together, we can simply export a variable (I like to call it CONFIG) in the user-wide postactivate set to $VIRTUAL_ENV/bin/postactivate. Then just edit $CONFIG from an activated virtualenv and you can manage environment variables there. So like,

[phil@notdeadyet ~] workon home-automation
(home-automation)[phil@notdeadyet home-automation] nano $CONFIG

and then in nano, like uh...

#!/bin/bash
# This hook is run after this virtualenv is activated.

export FRONT_DOOR_PASSCODE=1,2,3,4

The missing feature is that postactivate is only run once, when activating your virtualenv, so your environment variables will not be immediately altered when you edit $CONFIG. So you have to either deactivate-reactivate, or just source $CONFIG to apply your variables.

#!/bin/bash
# This hook is run after every virtualenv is activated.
export CONFIG=$VIRTUAL_ENV/bin/postactivate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment