How do you read environment variables safely?
BeginnerConceptOS, filesystem, subprocess & CLIs
Answer
import os
region = os.environ.get("AWS_REGION", "us-east-1") # optional with default
token = os.environ["GITHUB_TOKEN"] # required: KeyError if missing
debug = os.getenv("DEBUG", "false").lower() in {"1", "true", "yes"}
Environment values are always strings, so parse them explicitly (int(os.getenv("WORKERS", "4"))). Validate required variables at startup and fail fast with a clear message rather than deep inside the run. os.environ changes only affect the current process and its children.
More on OS, filesystem, subprocess & CLIs
`os.path` vs `pathlib`: which do you use and why?BeginnerHow do you walk a directory tree and find files?BeginnerWhat does `shutil` give you that `os` does not?BeginnerHow do you run an external command correctly with `subprocess`?BeginnerWhy is `shell=True` dangerous, and when is it acceptable?IntermediateHow do you handle a failed command and show useful output?Intermediate