How to read Windows environment variable value?(如何读取 Windows 环境变量值?)
问题描述
我试过了:
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 的值,如果不存在则返回值.值默认为无.
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 环境变量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何读取 Windows 环境变量值?


- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01