473,287 Members | 1,714 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 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 3769
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: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

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.