What am I doing wrong? How do I change the value of an environment
variable?
What you are missing is that os.environ is only populated from the
global process environment at process startup.
If you update os.environ the changes will be pushed into the global
process environment as well. But if you use os.putenv() instead,
bypassing os.environ, the changes will not show in os.environ.
To confirm that the global process environment is being updated, use
os.getenv().
Graham
You'll have to go through the Windows registry. Please have a look at the
following recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/55993
I also have my own routines based on that for getting and setting the path:
##################
import _winreg as winreg
import win32gui
import win32con
REG_KEY_PATH = r'SYSTEM\CurrentControlSet\Control\Session
Manager\Environment'
def set_path(pathval):
"""Set the PATH environment variable"""
try:
reg = winreg.ConnectRegistry(None,
win32con.HKEY_LOCAL_MACHINE)
key = winreg.OpenKey(reg,
REG_KEY_PATH,
0,
win32con.KEY_ALL_ACCESS)
winreg.SetValueEx(key,
'path',
0,
win32con.REG_EXPAND_SZ,
pathval)
win32gui.SendMessage(win32con.HWND_BROADCAST,
win32con.WM_SETTINGCHANGE,
0,
'Environment')
finally:
winreg.CloseKey(key)
winreg.CloseKey(reg)
def get_path():
"""Get the PATH environment variable"""
try:
reg = winreg.ConnectRegistry(None,
win32con.HKEY_LOCAL_MACHINE)
key = winreg.OpenKey(reg,
REG_KEY_PATH,
0,
win32con.KEY_ALL_ACCESS)
return winreg.QueryValueEx(key,
'path')[0]
finally:
winreg.CloseKey(key)
winreg.CloseKey(reg)
##################
Regards,
Ryan Ginstrom
Can you tell me what I am still missing please?
>>> import os
>>>
>>> os.getenv('PATH')
'C:\\WINNT\\system32;C:\\WINNT;C:\\WINNT\\System32\\Wbem;%C:\\WINNT%\
\system32;%C:\\WINNT%;%C:\\WINNT%\\System32\\Wbem'
>>>
>>> os.putenv('PATH', 'C:\\WINNT\\system32')
>>>
>>> os.getenv('PATH')