尝试使用以下方法:os.getenv('MyVar')os.getenv(varname[, value])
Return the value of the environment variable varname if it exists, or value if it doesn’t. value defaults to None.
Availability: most flavors of Unix, Windows
所以在测试之后:>>> import os
>>> os.environ['MyVar'] = 'Hello World!' # set the environment variable 'MyVar' to contain 'Hello World!'
>>> print os.getenv('MyVar')
Hello World!
>>> print os.getenv('not_existing_variable')
None
>>> print os.getenv('not_existing_variable', 'that variable does not exist')
that variable does not exist
>>> print os.environ['MyVar']
Hello World!
>>> print os.environ['not_existing_variable']
Traceback (most recent call last):
File "", line 1, in ?
File "/usr/lib/python2.4/UserDict.py", line 17, in __getitem__
def __getitem__(self, key): return self.data[key]
KeyError: 'not_existing_variable
如果环境变量存在,您的方法也可以工作。使用os.getenv的区别在于,它返回None(或给定值),而os.environ['MyValue']在变量不存在时给出KeyError异常。