The Python Oracle

How do I access environment variables in Python?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Peaceful Mind

--

Chapters
00:00 How Do I Access Environment Variables In Python?
00:12 Answer 1 Score 68
00:29 Accepted Answer Score 4682
00:59 Answer 3 Score 81
01:10 Answer 4 Score 368
01:28 Thank you

--

Full question
https://stackoverflow.com/questions/4906...

--

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.