Python os.environ 没有设置环境变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30006722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
os.environ not setting environment variables
提问by blokeley
I'm trying to set a Windows environment variable using Python.
我正在尝试使用 Python 设置 Windows 环境变量。
It seems that, contrary to the docs, os.environcan get environment variables but cannot set them. Try running these in a Windows Command Prompt:
似乎与文档相反,os.environ可以获取环境变量但不能设置它们。尝试在 Windows 命令提示符中运行这些:
This works:
这有效:
python -c "import os; print(os.environ['PATH'])"
This does not:
这不会:
python -c "import os; os.environ['FOO'] = 'BAR'"
Try typing set
in the Command Prompt. The environment variable FOO does not exist.
尝试set
在命令提示符中键入。环境变量 FOO 不存在。
How can I set a permanent Windows environment variable from Python?
如何从 Python 设置永久的 Windows 环境变量?
采纳答案by honza_p
os.environ[...] = ...
sets the environment variable only for the duration of the python process (or its child processes).
os.environ[...] = ...
仅在 python 进程(或其子进程)的持续时间内设置环境变量。
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.
为运行 Python 的 shell 设置变量并不容易(即不使用特定于操作系统的工具),当然也不可取。请参阅 aumo 的评论,了解解决该问题的替代方法和有些晦涩难懂的方法。