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
Thanks for sharing this post. Your post is really very helpful its students. python Online Training
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDeletekayseriescortu.com - alacam.org - xescortun.com
ReplyDelete