How do I access environment variables in Python?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World
--
Chapters
00:00 Question
00:17 Accepted answer (Score 4272)
00:53 Answer 2 (Score 332)
01:20 Answer 3 (Score 76)
01:52 Answer 4 (Score 76)
02:07 Thank you
--
Full question
https://stackoverflow.com/questions/4906...
Accepted answer links:
[os.environ]: https://docs.python.org/library/os.html#...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #environmentvariables
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World
--
Chapters
00:00 Question
00:17 Accepted answer (Score 4272)
00:53 Answer 2 (Score 332)
01:20 Answer 3 (Score 76)
01:52 Answer 4 (Score 76)
02:07 Thank you
--
Full question
https://stackoverflow.com/questions/4906...
Accepted answer links:
[os.environ]: https://docs.python.org/library/os.html#...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #environmentvariables
#avk47
ACCEPTED ANSWER
Score 4682
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))
ANSWER 2
Score 368
To check if the key exists (returns True or False)
'HOME' in os.environ
You can also use get() when printing the key; useful if you want to use a default.
print(os.environ.get('HOME', '/home/username/'))
where /home/username/ is the default
ANSWER 3
Score 81
Here's how to check if $FOO is set:
try:
os.environ["FOO"]
except KeyError:
print "Please set the environment variable FOO"
sys.exit(1)
ANSWER 4
Score 68
You can access the environment variables using
import os
print os.environ
Try to see the content of the PYTHONPATH or PYTHONHOME environment variables. Maybe this will be helpful for your second question.