Working with environment variables in Python

We use the Python os library.

Using os.environ is the preferred way. Avoiding using os.getenv('FOO') and os.putenv('FOO'), since the latter does not update os.environ.

Setup

Run this in the shell to setup the environment.

FOO=bar python main.py

# OR
export FOO=bar
python main.py

Read

import os


os.environ['FOO']
# bar

# Safely.
os.environ.get('FOO', 'fallback')
# bar

Update

import os


os.environ['FOO'] = 'bazz'