os.environ not setting environment variables [dupl

2019-02-13 18:14发布

This question already has an answer here:

I'm trying to set a Windows environment variable using Python.

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:

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.

How can I set a permanent Windows environment variable from Python?

1条回答
时光不老,我们不散
2楼-- · 2019-02-13 19:02

os.environ[...] = ... sets the environment variable only for the duration of the python process (or its child processes).

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.

查看更多
登录 后发表回答