Setting an Environment Variable in Virtualenv

setting an environment variable in virtualenv

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

How to set environment variables in virtualenv

while writing sitecustomize.py file and changing bin/python all are feasible solutions, I would suggest another method that does not involve directly change contents inside virutalenv, by simply install a .pth file:

./venv/lib/python2.7/site-packages/_set_envs.pth

with content:

import os; os.environ['FOO'] = 'bar'

test:

$ ./venv/bin/python -c "import os; print os.getenv('FOO')"
bar

the trick is, python will load every .pth file on startup, and if there is a line starts with import, this line will be get executed, allowing inject arbitrary code.

the advantage is, you could simply write a python package to install this .pth file with setuptools, install to the virtualenv you want to change.

Set environment variables when activating python virtual environment in windows

If you want to setup your development environment in VSCode you can simply add .env file with all secrets defined in project root directory. More details in docs

Is there a way to automatically load environment variables when activating venv?

A good practice is to use dotenv. You can load your environment by placing your environment variables into a file named .env, and whenever you would like to load an environment, just use the lines:

from dotenv import load_dotenv
load_dotenv()

This has the nicety that it only exists within the scope of you running a single script, since it essentially works like calling os.environ['variable'] = 'value' a number of times.



Related Topics



Leave a reply



Submit