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
Convert Columns to String in Pandas
Sorting by a Custom List in Pandas
Python - Typeerror: 'Int' Object Is Not Iterable
Django Reverse Lookup of Foreign Keys
Multiprocessing.Dummy in Python Is Not Utilising 100% Cpu
Parameter Substitution for a SQLite "In" Clause
Count Consecutive Occurences of Values Varying in Length in a Numpy Array
How to Add a New Column to a Spark Dataframe (Using Pyspark)
Convert Datetime to Unix Timestamp and Convert It Back in Python
How to Round the Minute of a Datetime Object
Is It Feasible to Compile Python to MAChine Code
Check If All Elements of a List Are of the Same Type
Typeerror: Worker() Takes 0 Positional Arguments But 1 Was Given
How to Count the Nan Values in a Column in Pandas Dataframe
How to Scrape a Website Which Requires Login Using Python and Beautifulsoup