Educating yourself does not mean that you were stupid in the first place; it means that you are intelligent enough to know that there is plenty left to 'learn'. -Melanie Joy

Sunday 3 February 2013

Reading environment variables in python

February 03, 2013 Posted by Dinesh 5 comments

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 

5 comments:

  1. Thanks for sharing this post. Your post is really very helpful its students. python Online Training

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete
  4. This comment has been removed by a blog administrator.

    ReplyDelete