Setting an environment variable in virtualenv
Define a temporary environment variable in a virtualenv session:
For variable persistence, append an export statement to bin/activate:
Let's enhance this approach with virtualenvwrapper and other tools.
Leveraging virtualenvwrapper's superpowers
Set up a long-lasting environment with virtualenvwrapper. It optimizes your workflow with helpful hooks such as postactivate and predeactivate.
Elevate your activation game with hooks
Populate your postactivate script:
This ensures your variable FOO gets a value every time your virtualenv activates, thus providing continuous reinforcement to your workspace.
Clear the environment gracefully with predeactivate:
This ensures not a trace of FOO, preventing your global environment from getting confused about its origin.
Reshuffle directories efficiently
Virtualenvwrapper enables you to create a symlink to your project directory within your virtualenv:
This allows quick switching between projects. Less navigation, more action!
Automate environment configuration
Mkvirtualenv from virtualenvwrapper is a power tool to auto-create symlinks, environment variables, and more on the fly:
Do it once, replicate it a thousand times.
Alternate routes for seamless integration
Direnv — the environment shape-shifter
Direnv automatically sets environment variables as soon as you enter a directory, like a perfect butler:
Ever in doubt? Check out direnv's GitHub for elaborate and exhaustive tweaks.
One shot, one kill: activate script modification
Modify the activate script inside bin of your virtualenv to quickly set an environment variable:
But remember, what's tattooed should be erased. Include the corresponding unset command in the deactivate function.
Edge cases and their antidotes
When playing with symlinks or shell integrations, always backup your environment variables. Treat them delicately to prevent chaos:
Then, bring back the old values on deactivation using the predeactivate hook:
Soak up the wisdom of documentation
Seize the guidance from official documentation for in-depth understanding and prolific usage.
Was this article helpful?