env variable set using _winreg.SetValueEx() doesn't show w/ os.environ

Discussion in 'Python' started by Erick Bodine, Dec 16, 2003.

  1. Erick Bodine

    Erick Bodine Guest

    I am trying to set a new environment variable on a W2k machine with
    only partial success. The name("SSID") and value("ASIM") show up
    correctly in the registry and when I go to "System
    Properties"->Advanced->"Environment Variables". However, if I open a
    console and type 'set', "SSID" is not listed; also if I open a python
    shell and do os.environ["SSID"] the variable is not found. What am I
    doing wrong???

    import _winreg

    system = r"SYSTEM\CurrentControlSet\Control\Session
    Manager\Environment"
    registry = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
    env_key = _winreg.OpenKey(registry, system, 0, _winreg.KEY_SET_VALUE)

    key = "SSID"
    value = "ASIM"

    try:
    _winreg.SetValueEx(env_key, key, 0, _winreg.REG_EXPAND_SZ, value)
    except EnvironmentError:
    print "Encountered problems writing (%s) into the registry" % key

    _winreg.CloseKey(env_key)
    _winreg.CloseKey(registry)

    I have tried this using ActivePython-2.3.2-232 and Python-2.3.2 w/ the
    same results.

    Thanks,

    ERick
    Erick Bodine, Dec 16, 2003
    #1
    1. Advertising

  2. Erick Bodine

    Matt Gerrans Guest

    Here is what I do; it works well on WinXP/2K/NT and with Python 2.2 and 2.3.
    (Of course, it wouldn't work for a "limited user" account -- for that case,
    it could be modified to use HKEY_CURRENT_USER instead, but it would only be
    able to change the "user variables" not the system variables). The code
    below is for updating the path variable, but you can modify it to work for
    any variable.

    Also, as you may know, this doesn't change the variable settings for the
    current process, just for all new processes and those few smart ones that
    actually pay attention to the broadcast message. If you want to also
    change variables for a sub-process you are launching, then additiobnally
    modifing those via os.environ will do the trick. If you want to add/modify
    variables for a process that runs *after* yours (in a shell script, for
    example), that's the tough one (but it can "kind of" be done by jumping
    through some silly hoops).

    """
    Appends a chunk to the path in a way that puts it in effect as soon as
    possible.

    Command line syntax:
    appendToSystemPath [some part to append] [another var]

    If you specify "another var" it means you want to append that environment
    variable instead. This is only useful if that other variable is a
    path-like variable, such as classpath, pythonpath, pathext, etc.
    """
    #---------------------------------------------------------------------------
    --
    #
    #
    #---------------------------------------------------------------------------
    --
    versions = ['2.10.5.1','3.8.18.1']
    version = versions[-1]

    from _winreg import *
    from win32gui import SendMessageTimeout
    from win32con import HWND_BROADCAST
    from win32con import WM_SETTINGCHANGE
    import os, sys

    from win32con import WM_STYLECHANGING
    from win32con import WM_STYLECHANGED
    from win32con import GWL_EXSTYLE

    debug = os.environ.get('debug','0') == '1'

    #---------------------------------------------------------------------------
    --
    # addToSystemPath()
    #
    # Dependencies: _winreg, win32api, win32con, os.
    #
    # Description: Adds an item to the system path; currently, the effect will
    # will not be promulgated properly until after a reboot,
    # because the documented method of doing this does not work.
    # The new chunk will only be added if it is not already in the
    # path (a case-insensitive search is done to verify this).
    # Parameters: newPart: The chunk to add to the path.
    # Returns: 1 if all went well.
    # History: 2002-07-16 mfg: Created; also sent a acrimonious email to
    # Microsoft about thier inadequated documentation with regards
    # to setting system variables.
    #---------------------------------------------------------------------------
    --
    def addToSystemPath(newPart,item='path'):
    keypath = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
    result = 1
    try:
    if debug: print 'Opening',keypath
    key = OpenKey( HKEY_LOCAL_MACHINE, keypath )
    if debug: print 'Querying',item
    path,dataType = QueryValueEx( key, item )
    key.Close()
    print 'Current %s is: %s' % (item,path)
    if path.lower().find(newPart.lower()) == -1:
    if debug: print 'It does not contain',newPart
    path = os.pathsep.join( path.split(os.pathsep) + [newPart] )

    key = OpenKey( HKEY_LOCAL_MACHINE, keypath, 0, KEY_SET_VALUE )
    SetValueEx( key, item, 0, dataType, path )
    key.Close()
    print 'Set %s in registry.' % path
    # Windows documentation says that this works, but it doesn't:
    if debug: print 'Broadcasting settings change message...'
    SendMessageTimeout( HWND_BROADCAST, WM_SETTINGCHANGE, 0,
    "Environment", 0, 1000 )
    print 'New %s is:' % item
    print path
    else:
    print 'Nothing to do -- it is already there!'
    if debug: print 'All done!'
    except:
    if debug: print 'Bronk!'
    result = 0
    return result

    if __name__ == '__main__':
    if len(sys.argv) > 1:
    if len(sys.argv) > 2:
    addToSystemPath(sys.argv[1],sys.argv[2])
    else:
    addToSystemPath(sys.argv[1])
    else:
    print __doc__

    "Erick Bodine" <> wrote in message
    news:...
    > I am trying to set a new environment variable on a W2k machine with
    > only partial success. The name("SSID") and value("ASIM") show up
    > correctly in the registry and when I go to "System
    > Properties"->Advanced->"Environment Variables". However, if I open a
    > console and type 'set', "SSID" is not listed; also if I open a python
    > shell and do os.environ["SSID"] the variable is not found. What am I
    > doing wrong???
    >
    > import _winreg
    >
    > system = r"SYSTEM\CurrentControlSet\Control\Session
    > Manager\Environment"
    > registry = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
    > env_key = _winreg.OpenKey(registry, system, 0, _winreg.KEY_SET_VALUE)
    >
    > key = "SSID"
    > value = "ASIM"
    >
    > try:
    > _winreg.SetValueEx(env_key, key, 0, _winreg.REG_EXPAND_SZ, value)
    > except EnvironmentError:
    > print "Encountered problems writing (%s) into the registry" % key
    >
    > _winreg.CloseKey(env_key)
    > _winreg.CloseKey(registry)
    >
    > I have tried this using ActivePython-2.3.2-232 and Python-2.3.2 w/ the
    > same results.
    >
    > Thanks,
    >
    > ERick
    Matt Gerrans, Dec 16, 2003
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    11
    Views:
    602
  2. Ankit Mehta
    Replies:
    1
    Views:
    1,389
    Simon Brooke
    Sep 29, 2006
  3. Replies:
    9
    Views:
    706
    Peter Otten
    Feb 27, 2007
  4. gert
    Replies:
    0
    Views:
    455
  5. TDR
    Replies:
    3
    Views:
    161
    Daniel Berger
    Aug 31, 2007
Loading...

Share This Page