setting an environment variable in virtualenv
Solution 1:
In case you're using virtualenvwrapper (I highly recommend doing so), you can define different hooks (preactivate, postactivate, predeactivate, postdeactivate) using the scripts with the same names in $VIRTUAL_ENV/bin/
. You need the postactivate hook.
$ workon myvenv
$ cat $VIRTUAL_ENV/bin/postactivate
#!/bin/bash
# This hook is run after this virtualenv is activated.
export DJANGO_DEBUG=True
export S3_KEY=mykey
export S3_SECRET=mysecret
$ echo $DJANGO_DEBUG
True
If you want to keep this configuration in your project directory, simply create a symlink from your project directory to $VIRTUAL_ENV/bin/postactivate
.
$ rm $VIRTUAL_ENV/bin/postactivate
$ ln -s .env/postactivate $VIRTUAL_ENV/bin/postactivate
You could even automate the creation of the symlinks each time you use mkvirtualenv.
Cleaning up on deactivate
Remember that this wont clean up after itself. When you deactivate the virtualenv, the environment variable will persist. To clean up symmetrically you can add to $VIRTUAL_ENV/bin/predeactivate
.
$ cat $VIRTUAL_ENV/bin/predeactivate
#!/bin/bash
# This hook is run before this virtualenv is deactivated.
unset DJANGO_DEBUG
$ deactivate
$ echo $DJANGO_DEBUG
Remember that if using this for environment variables that might already be set in your environment then the unset will result in them being completely unset on leaving the virtualenv. So if that is at all probable you could record the previous value somewhere temporary then read it back in on deactivate.
Setup:
$ cat $VIRTUAL_ENV/bin/postactivate
#!/bin/bash
# This hook is run after this virtualenv is activated.
if [[ -n $SOME_VAR ]]
then
export SOME_VAR_BACKUP=$SOME_VAR
fi
export SOME_VAR=apple
$ cat $VIRTUAL_ENV/bin/predeactivate
#!/bin/bash
# This hook is run before this virtualenv is deactivated.
if [[ -n $SOME_VAR_BACKUP ]]
then
export SOME_VAR=$SOME_VAR_BACKUP
unset SOME_VAR_BACKUP
else
unset SOME_VAR
fi
Test:
$ echo $SOME_VAR
banana
$ workon myenv
$ echo $SOME_VAR
apple
$ deactivate
$ echo $SOME_VAR
banana
Solution 2:
Update
As of 17th May 2017 the README of autoenv states that direnv is probably the better option and implies autoenv is no longer maintained.
Old answer
I wrote autoenv to do exactly this:
https://github.com/kennethreitz/autoenv