Welcome, guest | Sign In | My Account | Store | Cart

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

Python, 25 lines
 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)

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.

1 comment

Peter Schwalm 19 years, 7 months ago  # | flag

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))
Created by Wolfgang Strobl on Mon, 21 May 2001 (PSF)
Python recipes (4591)
Wolfgang Strobl's recipes (3)

Required Modules

Other Information and Tasks