472,984 Members | 2,650 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,984 software developers and data experts.

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

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
Jul 18 '05 #1
1 3734
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" <er**********@comcast.net> wrote in message
news:8d**************************@posting.google.c om...
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

Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: sebastien.hugues | last post by:
Hi I would like to retrieve the application data directory path of the logged user on windows XP. To achieve this goal i use the environment variable APPDATA. The logged user has this name:...
8
by: Olaf Meyer | last post by:
Sometimes if find it clumsy unsing the following approach building strings: cmd = "%s -start %s -end %s -dir %s" % (executable, startTime, endTime, directory) Especially if you have a lot of...
4
by: marc.wyburn | last post by:
Hi, I am trying to move away from Windows only scripting to Python. I've written a quick script that will pull the product version from the client registry. I can get the IP addresses from a file...
11
by: jim.eggleston | last post by:
Windows doesn't have a HOME environment variable, but it does have HOMEDRIVE and HOMEPATH. Could Windows versions of Python automatically populate os.environ with HOME, where HOME =...
10
by: mirandacascade | last post by:
O/S: Win2K Vsn of Python:2.4 Based on a search of other posts in this group, it appears as though os.environ is one way to obtain the PATH environment variable. My questions: 1) is it...
2
by: black_13 | last post by:
I have included a small script the reproduces the error I am having in larger script. The line 'hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,name)' seems to be causing the error but im not...
4
by: Stephen Cattaneo | last post by:
Hello all, I am attempting to execute an automated test (written in Python) via cron. I have to check the HOSTNAME variable as part of the test, oddly under cron the HOSTNAME environment...
0
by: Cameron Simpson | last post by:
On 17Aug2008 21:25, John Nagle <nagle@animats.comwrote: Because $HOSTNAME is a bash specific variable, set by bash but NOT EXPORTED! Like $0 and a bunch of other "private" variables, subprocesses...
9
by: Michel Leunen | last post by:
Hi, Could someone explain me what I'm doing wrong here? I'm trying to retrieve the value of an environment variable in Ubuntu 8.04 like this: 'michel' This works but this doesn't: ...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.