How do I access environment variables in Python?

Environment variables are accessed through os.environ:

import os

To see a list of all environment variables:


If a key is not present, attempting to access it will raise a KeyError. To avoid this:

# Returns `None` if key doesn't exist

# Returns `default_value` if key doesn't exist
print(os.environ.get('KEY_THAT_MIGHT_EXIST', default_value))

# Returns `default_value` if key doesn't exist
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))

Leave a Comment