15

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?

blokeley
  • 6,726
  • 9
  • 53
  • 75
  • 4
    See http://stackoverflow.com/questions/235435/environment-variables-in-python-on-linux or http://stackoverflow.com/questions/488366/how-do-i-make-environment-variable-changes-stick-in-python – aumo May 02 '15 at 19:59
  • 3
    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 May 02 '15 at 20:11
  • 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 May 02 '15 at 22:06
  • By the way, this is how environment variables work everywhere -- in every language and every operating system I'm aware of. Nothing specific to Python. – Charles Duffy May 02 '15 at 22:07
  • 2
    @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 May 02 '15 at 22:52
  • @eryksun: True, but hardly pertinent to the question immediately at hand. – Charles Duffy May 02 '15 at 23:37
  • 2
    @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 May 03 '15 at 00:32
  • For windows I can recommend a module to set variables through registry. Also has CLI app: https://github.com/beliaev-maksim/py_setenv this has good control on user/system level and does not have limit in length as setx – Beliaev Maksim Feb 12 '21 at 19:34

1 Answers1

26

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.

honza_p
  • 2,073
  • 1
  • 23
  • 37