如何读取Windows环境变量值? [英] How to read Windows environment variable value?
问题描述
我尝试过:
os.environ['MyVar']
但这没有用!
是否有适合所有操作系统的方法?
But it did not work! Is there any way suitable for all operating systems?
推荐答案
尝试使用以下内容:
os.getenv('MyVar')
来自文档:
os.getenv(varname [,value])
os.getenv(varname[, value])
返回环境变量的值varname(如果存在)或value(如果不存在)。值默认为无。
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环境变量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!