12
votes

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
Think of this as a feature for your protection: nothing that a subshell does can mess with the program that calls it. This allows you to call./create subshells with confidence that it won't interfere with any of your environment variables. - John1024
If you want to check whether os.environ is creating environment variables, checking from your shell is the wrong tool. Use Process Explorer to inspect the state of your Python process, and you'll see that these truly are created, even though they don't outlive the process that creates them. - Charles Duffy
@CharlesDuffy, what's specific to Python is that the os.environ dict can get out of sync with the actual process environment, e.g. a DLL function could call _putenv. - Eryk Sun
@CharlesDuffy, this sync quirk is noteworthy; it's something every Python programmer should know, and so bears repeating even as a tangential comment. Also, technically the environment variables set in the current process can outlive it by spawning child processes. ;-) - Eryk Sun

1 Answers

24
votes

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.