os.environ not setting environment variables(os.environ 没有设置环境变量)
问题描述
我正在尝试使用 Python 设置 Windows 环境变量.
I'm trying to set a Windows environment variable using Python.
似乎与文档相反,os.environ 可以获取环境变量但不能设置它们.尝试在 Windows 命令提示符中运行这些:
It seems that, contrary to the docs, os.environ can get environment variables but cannot set them. Try running these in a Windows Command Prompt:
这行得通:
python -c "import os; print(os.environ['PATH'])"
这不是:
python -c "import os; os.environ['FOO'] = 'BAR'"
尝试在命令提示符中键入 set
.环境变量 FOO 不存在.
Try typing set
in the Command Prompt. The environment variable FOO does not exist.
如何通过 Python 设置永久的 Windows 环境变量?
How can I set a permanent Windows environment variable from Python?
推荐答案
os.environ[...] = ...
仅在 python 进程期间(或它的子进程).
os.environ[...] = ...
sets the environment variable only for the duration of the python process (or its child processes).
为运行 Python 的 shell 设置变量并不容易(即不使用特定于操作系统的工具),当然也不可取.请参阅 aumo 的评论,了解解决问题的替代方法和有些晦涩的方法.
It is not easily (i.e. without employing OS-specific tools) possible and surely not advisable to set the variable for the shell from which you run Python. See aumo's comment for alternative and somewhat obscure approaches to the problem.
这篇关于os.environ 没有设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:os.environ 没有设置环境变量


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