HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCritical

How can I access environment variables in Python?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
accesshowpythonenvironmentcanvariables

Problem

How can I get the value of an environment variable in Python?

Solution

Environment variables are accessed through os.environ:

import os
print(os.environ['HOME'])


To see a list of all environment variables:

print(os.environ)


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

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

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

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

Code Snippets

import os
print(os.environ['HOME'])
print(os.environ)
# Returns `None` if the key doesn't exist
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))

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

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

Context

Stack Overflow Q#4906977, score: 4853

Revisions (0)

No revisions yet.