如何在python中读取Windows环境变量值? [英] How to read windows environment variable value in python?
问题描述
我尝试过:
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.
这篇关于如何在python中读取Windows环境变量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!