setting an environment variable in virtualenv setting an environment variable in virtualenv python python

setting an environment variable in virtualenv


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=Trueexport S3_KEY=mykeyexport S3_SECRET=mysecret$ echo $DJANGO_DEBUGTrue

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_VARfiexport 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_BACKUPelse    unset SOME_VARfi

Test:

$ echo $SOME_VARbanana$ workon myenv$ echo $SOME_VARapple$ deactivate$ echo $SOME_VARbanana


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


You could try:

export ENVVAR=value

in virtualenv_root/bin/activate.Basically the activate script is what is executed when you start using the virtualenv so you can put all your customization in there.