Skip to content

Instantly share code, notes, and snippets.

@jerrykan
Last active December 31, 2015 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jerrykan/8048921 to your computer and use it in GitHub Desktop.
Save jerrykan/8048921 to your computer and use it in GitHub Desktop.
Simple wrapper around virtualenv activate to set/unset environment variables
# Wrapper around virtualenv activate to set/unset environment variables
#
# Update the location of the virtualenv (VENV_DIR) and the environment variables
# to be set at the end of the script. Then use this script to init the
# virtualenv instead of the virtualenv version:
#
# $ source activate
#
# Virtualenv location
VENV_DIR="$(dirname $BASH_SOURCE)/venv"
# Store origininal env
_get_env()
{
env | cut -d "=" -f 1 | sort
}
# Activate the virtualenv
source "$VENV_DIR/bin/activate"
# Rename original deactivate function and redefine it as a wrapper function
eval "$(echo "orig_deactivate()"; declare -f deactivate | tail -n +2)"
deactivate()
{
# Deactivate the virtualenv
orig_deactivate
# Unset custom environment variables set at the end of the script
for V in $(comm -13 <(echo "$_ORIG_ENV_VARS") <(echo "$(_get_env)")); do
unset $V
done
# We no longer need this function
unset deactivate
}
# Store existing env vars
_ORIG_ENV_VARS=$(_get_env)
# Set custom environment variables
export CUSTOM_VAR="some value"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment