Skip to content

Instantly share code, notes, and snippets.

@tanyaschlusser
Last active October 27, 2018 14:32
Show Gist options
  • Save tanyaschlusser/ab9dd7dc4d761a04bd02495394f288bd to your computer and use it in GitHub Desktop.
Save tanyaschlusser/ab9dd7dc4d761a04bd02495394f288bd to your computer and use it in GitHub Desktop.
Virtualenvwrapper postactivate and predeactivate (python)
ENVVAR1=value
ENVVAR2="value 2"
#COMMENTED="Lines starting with hash will be skipped."

postactivate and predeactivate for Virtualenvwrapper

  • The contents of postactivate and predeactivate go into their respective placeholders in $WORKON_HOME
  • The .env file should be formatted as shown and placed in the top directory of your environment, e.g.
    $WORKON_HOME/my_environment

Then after workon my_environment the new environment variables will be set, and after deactivate the old ones will be restored.

#!/bin/bash
# Populates environment variables in a .env file in the virtual env directory,
# proactively saving old variables with the same name to _OLD__$varname
if [ -f $VIRTUAL_ENV/.env ]
then
for line in `sed '/^#.*/d' $VIRTUAL_ENV/.env`
do
varname="$(cut -d'=' -f1 <<<$line)"
echo " setting envvar $varname"
if `env | grep -q $varname`
then
export _OLD__$varname=${!varname}
fi
export $line
done
fi
#!/bin/bash
# Unsets environment variables in a .env file in the virtual env directory,
# restoring saved variables from _OLD__$varname
if [ -f $VIRTUAL_ENV/.env ]
then
for line in `sed '/^#.*/d' $VIRTUAL_ENV/.env`
do
varname="$(cut -d'=' -f1 <<<$line)"
oldvarname="_OLD__$varname"
if `env | grep -q $oldvarname`
then
echo "removing envvar $oldvarname and resetting $varname"
export $varname=${!oldvarname}
unset $oldvarname
else
echo "removing envvar $varname"
unset $varname
fi
done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment