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
本文介绍了如何使用Python中的os模块来访问环境变量。通过os.environ可以获取环境变量的值,但若变量不存在则会引发KeyError。推荐使用os.getenv方法,它允许设置默认值,避免异常并提供更安全的访问方式。
676

被折叠的 条评论
为什么被折叠?



