Changing the path on Win2k/XP

Bjorn Pettersen BPettersen at NAREX.com
Tue Jun 11 12:27:48 EDT 2002


> From: David LeBlanc [mailto:whisper at oz.net] 
>
> > From: Bjorn Pettersen 
> > Subject: Changing the path on Win2k/XP
> >
> > Is there a way to change the path on Win2k/XP through Python? (I'm 
> > trying to write a .dll deployment script for our production 
> > department, and I'd like to give them a "one button" install...)
>
> 
> You should be able to modify the path on Win2k/XP by 
> modifying the associated registry key(s). There is one for 
> the "system" environment one for the "per user" environment. 
> This won't take effect for the current process though, but 
> only for new ones (at least comd.exe processes).
> 
> Take a look in (changes depending on user logged in):
> 	HKEY_CURRENT_USER\Environment
> and:
> 	HKEY_LOCAL_MACHINE\SYSTEM\Current Control Set\Control\Session
> Manager\Environment	
> HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session
> Manager\Environment	
> HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Control\Session
> Manager\Environment
> 
> Of the 3 in HKLM\SYSTEM, I think only "Current Control Set" 
> is relevent.
> 
> You can modify these with the _winreg package ("import 
> _winreg"). BE VERY CAUTIOUS! Incorrect modifications of your 
> registry can render your machine unusable and possibly 
> requiring an OS reinstall. There is a procedure for creating 
> a backup copy of your registry and a backup disk and I 
> suggest you do both until you are comfortable with what you're doing.

Thanks! Hers's what I came up with (use at your own risk etc. etc.)

-- bjorn

import _winreg

def setpath(entry):
    assert(type(entry) == unicode)
    assert(entry[-1] == u';')
    SYSTEM = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SYSTEM')
    CurrentControlSet = _winreg.OpenKey(SYSTEM, 'CurrentControlSet')
    Control = _winreg.OpenKey(CurrentControlSet, 'Control')
    SessionManager = _winreg.OpenKey(Control, 'Session Manager')
    Environment = _winreg.OpenKey(SessionManager, 'Environment')
    EnvironmentWrite = _winreg.OpenKey(SessionManager, 'Environment', 0,
_winreg.KEY_SET_VALUE)
    path, type = _winreg.QueryValueEx(Environment, 'Path')
    path = entry + path
    assert(len(path) < 2048)
    _winreg.SetValueEx(EnvironmentWrite, 'Path', 0,
_winreg.REG_EXPAND_SZ, path)
    _winreg.CloseKey(EnvironmentWrite)
    _winreg.CloseKey(Environment)
    _winreg.CloseKey(SessionManager)
    _winreg.CloseKey(Control)
    _winreg.CloseKey(CurrentControlSet)
    _winreg.CloseKey(SYSTEM)






More information about the Python-list mailing list