Reading environment variables in python
reference:
http://itsjustsosimple.blogspot.jp/2013/02/reading-environment-variables-in-python.html
The
os
module contains an interface to operating system-specific functions. this module can be used to access environment variables.
We can go with os.environ to get the value of environment variable.
import os
print os.environ['HOME']
but there is a catch, this method will raise
KeyError variable does not exist
>>> print os.environ['HOME_NOT_EXIST']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/UserDict.py", line 23, in __getitem__
raise KeyError(key)
KeyError: 'HOME_NOT_EXIST'
So it is better to go with os.getenv. this return None if key/environment variable does not exist. and if we require we can return default values too.
print os.getenv('KEY') #returns None if KEY doesn't exist
print os.getenv('KEY', 0) #will return 0 if KEY doesn't exist