4

I need build a system environ variable, and I use os.putenv(key, value) to build one, then print os.getenv(key), the console outputs None.

But the console outputs value (here is print os.getenv(key) or print os.environ[key]) when I use os.environ[key] = value to build it.

However, the key and the value are not in the dictionary if print os.environ.

Why can I not build the system environment variable successfully? I use Windows 7 and Python 2.7.5.

Martin Geisler
  • 72,968
  • 25
  • 171
  • 229
Aurora Wu
  • 65
  • 1
  • 6
  • It's a good practice to restore the environment variables at function completion. You may need something like the `modified_environ` context manager describe in this [question](http://stackoverflow.com/a/34333710/1513933) to restore the environment variables. – Laurent LAPORTE May 10 '17 at 20:11

1 Answers1

3

If you read the documentation you will get the answer to why os.putenv does not work:

This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly.

If the platform supports the putenv() function, this mapping may be used to modify the environment as well as query the environment. putenv() will be called automatically when the mapping is modified.

Note Calling putenv() directly does not change os.environ, so it’s better to modify os.environ.

Martin Geisler
  • 72,968
  • 25
  • 171
  • 229
Matthew Graves
  • 3,226
  • 1
  • 17
  • 20
  • okay, I use os.environ[key]=value to build a system environ variable successfully in python shell. But why does not the system environ variable exist if I shutdown the python shell? – Aurora Wu Jun 27 '13 at 04:54
  • I knew that the system environ variable only exists in current python shell, I must import _winreg module to build the system environ variable if I want the system environ variable to save in windows operating-system. BTW, thanks a lot for your patient interpretation. :D – Aurora Wu Jun 27 '13 at 05:11