问题描述
我试过了:
os.environ['MyVar']
但它没有用!有没有适合所有操作系统的方法?
But it did not work!Is there any way suitable for all operating systems?
推荐答案
尝试使用以下方法:
os.getenv('MyVar')
来自文档:
os.getenv(varname[, value])
如果存在则返回环境变量 varname 的值,如果不存在则返回值.值默认为无.
Return the value of the environment variable varname if it exists, or value if it doesn’t. value defaults to None.
可用性:大多数版本的 Unix、Windows
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 "<stdin>", 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 异常.
Your method would work too if the environmental variable exists. The difference with using os.getenv
is that it returns None
(or the given value), while os.environ['MyValue']
gives a KeyError exception when the variable does not exist.
这篇关于如何读取 Windows 环境变量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!