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 环境变量值?


基础教程推荐
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01