473,466 Members | 1,395 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

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 3781
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: ...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.