📝 Edit page
➕ Add page
Environment
Working with environment variables in Python
We typicall use the Python os library for environment variables.
Using os.environ
is the preferred way. Avoiding using os.getenv('FOO')
and os.putenv('FOO')
, since the latter does not update os.environ
.
Related - see dot-env cheatsheet for reading environment variables in your Python application.
Read values
Set the values in Bash first:
$ FOO=bar python main.py
Or
$ export FOO=bar
$ python main.py
Read the values in Python:
import os
os.environ['FOO']
# bar
# Safely in case the variable is not set.
os.environ.get('FOO', 'fallback-value')
# fallback-value
Set values
import os
os.environ['FOO'] = 'bazz'
os.environ['FOO']
# 'bazz'