PDA

View Full Version : env variables set in Python/Windows



daland
22nd July 2010, 21:56
I want to set an env variable in python and have it remain after the python session ends.
Another words it would show up in the Environment Variables panel in the System Properties pane. When I try to use os.putenv command it only works within the session.

Any ideas? I just want to set an env variable from python in Windows. (64bit)

thanks

david

jaystevens
12th April 2011, 06:55
Look at pywin32\'s modules: _winreg, win32gui, win32con

You can change the system default environment variable by directly editing the registry and then issuing a system \"notification\" that the environment has changed. This will not have any affect on already running/started programs or command shells.

system environment variables are stored in:
\'HKLM\\\\SYSTEM\\\\CurrentControlSet\\\\Control\\ \\Session Manager\\\\Environment\'

set reg key:
reg = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, \'SYSTEM\\\\CurrentControlSet\\\\Control\\\\Sessio n Manager\\\\Environment\', 0, _winreg.KEY_READ)
_winreg.SetValueEx(reg, \'environment variable\', 0, _winreg.REG_SZ, \'envirment value\')
_winreg.CloseKey(reg)

and to issue the notification:
win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, \'Environment\')