PythonMastery

How do I read an environment variable in Python?

os.environ.get('NAME', 'default') for optional settings; os.environ['NAME'] for required ones, so a missing value fails at start-up. Values are strings.

os.environ behaves like a dictionary of the environment variables your program was started with.

python
import os

os.environ["APP_MODE"] = "production"       # pretend it was set outside Python

print(os.environ.get("APP_MODE", "development"))
print(os.environ.get("LOG_LEVEL", "INFO"))   # not set, so the default
output
production
INFO

Pick the form by asking "can the program work without this?"

Every value is a string

The environment only holds text. A port, a timeout or a flag has to be converted, and booleans need care:

python
import os

os.environ["PORT"] = "8080"
os.environ["DEBUG"] = "false"

port = int(os.environ.get("PORT", "8000"))
debug = os.environ.get("DEBUG", "false").lower() in ("1", "true", "yes")

print(port + 1)
print(debug)
print(bool("false"))   # the trap: any non-empty string is True
output
8081
False
True

bool(os.environ["DEBUG"]) is True for "false", "0" and "no", because they're all non-empty strings. Compare the text instead.

Setting one

On your own machine, set it in the terminal before starting Python:

bash
# macOS / Linux
export SHOP_API_KEY="sk-live-..."

# Windows PowerShell
$env:SHOP_API_KEY = "sk-live-..."

For a project, most people keep them in a .env file and load it with python-dotenv (pip install python-dotenv):

python · run on your machine
from dotenv import load_dotenv
import os

load_dotenv()                       # reads .env in the current folder
api_key = os.environ["SHOP_API_KEY"]

Add .env to .gitignore before your first commit. A key that reaches GitHub has to be treated as stolen, even if you delete it a minute later; the secrets lesson covers what to do instead.

Go deeper: Environment Variables & Configuration, Secrets Management for Python Apps, KeyError: 'X', The Terminal for Python Developers

More short answers

all questions