Issue
How do 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 key doesn't exist
print(os.environ.get('KEY_THAT_MIGHT_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))
Answered By - Rod Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.