ActiveState Code

Recipe 55993: Environment manipulation on Windows NT or Windows 2000


Display environment variables, then append C:\ to PATH. Example program, uses _winreg.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import _winreg
x=_winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE)
y= _winreg.OpenKey(x,
 r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")
print "Your environment variables are"
print "#","name","value","type"
for i in range(1000):
    try:
        n,v,t=_winreg.EnumValue(y,i)
        print i,n,v,t
    except EnvironmentError:
        print "You have",i,"Environment variables"
        break
print "Your PATH was "    
path = _winreg.QueryValueEx(y,"path")[0]
print path
_winreg.CloseKey(y)
# Reopen Environment key for writing.
y=_winreg.OpenKey(x,
 r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment",
 0,_winreg.KEY_ALL_ACCESS)
# now append C:\ to the path
_winreg.SetValueEx(y,"path",0,_winreg.REG_EXPAND_SZ,path+";C:\\")
_winreg.CloseKey(y)
_winreg.CloseKey(x)

Discussion

Install utilities may have a need for changing the path in the registry. _winreg (from the standard library) is the right tool for this endeavour. According to docs, it is desired to become complemented by a more abstract winreg module, sometime in the future.

This example displays and modifies the _system_ environment variables, not those of the current user.

Comments

  1. 1. At 5:55 a.m. on 31 aug 2004, Peter Schwalm said:

    environment changes do not have an effect immediately. The changes made to the environment in the proposed way do not have an effect immediately, even not for a newly start cmd.exe. The following function refreshEnvironment(), if called after setting the environment in the registry lets newly started programs (cmd.exe) "see" the new environment values.

    Thanks for this method to Geoffrey Faivre-Malloy and Ronny Lipshitz. See http://www.installsite.org/files/PathSetup.zip

    def refreshEnvironment():
        HWND_BROADCAST      = 0xFFFF
        WM_SETTINGCHANGE    = 0x001A
        SMTO_ABORTIFHUNG    = 0x0002
        sParam              = "Environment"
    
        import win32gui
        res1, res2          = win32gui.SendMessageTimeout(HWND_BROADCAST,
                                WM_SETTINGCHANGE, 0, sParam, SMTO_ABORTIFHUNG, 100)
        if  not res1:
            print ("result %s, %s from SendMessageTimeout" % (bool(res1), res2))
    

Sign in to comment