How to get an environment variable in Python?

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

asked May 23, 2017 by dtivl (2,500 points)

1 Answer

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')
answered May 27, 2017 by dtivl (2,500 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...