This question already has an answer here:
这个问题在这里已有答案:
- How do I make environment variable changes stick in Python? 11 answers
如何在Python中使环境变量更改? 11个答案
I'm trying to set a Windows environment variable using Python.
我正在尝试使用Python设置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:
似乎与文档相反,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环境变量?
1 个解决方案
#1
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.
不容易(即不使用特定于OS的工具)可能并且肯定不建议为运行Python的shell设置变量。请参阅aumo对该问题的替代和有些模糊方法的评论。
#1
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.
不容易(即不使用特定于OS的工具)可能并且肯定不建议为运行Python的shell设置变量。请参阅aumo对该问题的替代和有些模糊方法的评论。