How to get an environment variable in Python?

In Python, how to get the value (string) of an environment variable?

In Python, all environment variables can be accessed directly through os.environ

import os
print os.environ['HOME']

If the environment variable is not present, it will raise a KeyError.

You can use get to return None if the environment variable is not present:

print os.environ.get('ENV_MIGHT_EXIST')

os.getenv() is a handy function. It can give a default value instead or None

# return the default value if the environment variable is not present
print os.getenv('ENV_MIGHT_EXIST', 'ENV_DEFAULT_VAL')

# return `None` if the environment variable is not present
print os.getenv('ENV_MIGHT_EXIST')
Leave a Reply

Your email address will not be published. Required fields are marked *