How to use os.putenv() ?

Ryan Ginstrom software at ginstrom.com
Wed Aug 29 22:00:56 EDT 2007


> On Behalf Of google at tyeon.com
> What am I doing wrong?  How do I change the value of an 
> environment variable?

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




More information about the Python-list mailing list