问题描述
我正在尝试使用 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 没有设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!