Deleting a Windows Registry Value with Python
I would like to delete values from the registry in Windows using Python, but I don't understand what is the sub_key in the python documentation:
I have the following code, which I would like to use:
def del_env(name):
key = OpenKey(HKEY_CURRENT_USER, 'Environment', 0, KEY_ALL_ACCESS)
#SetValueEx(key, name, 0, REG_EXPAND_SZ, value)开发者_运维知识库
DeleteKey(key, ???) # what goes where the ??? are
CloseKey(key)
SendMessage(
win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')
This function should be used as
del_env("SOMEKEY")
p.s I forgot to mention, if I use:
deleteKey(key,"")
All environment variables in the session are erased ...
Thanks in advance, Oz
My Glorious fail:
: C:\etc\venus\current\bin>python.bat
Python 2.4.4 (#0, Jun 5 2008, 09:22:45) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import _winreg
>>> key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,r"Environment")
>>> _winreg.DeleteKey(key,"OZ")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
WindowsError: [Errno 2] Das System kann die angegebene Datei nicht finden
Use DeleteValue
instead of DeleteKey
as @Philipp mentioned in the comments:
def del_env(name):
key = OpenKey(HKEY_CURRENT_USER, 'Environment', 0, KEY_ALL_ACCESS)
DeleteValue(key, name)
CloseKey(key)
SendMessage(
win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')
I think DeleteKey takes the parent to the key you want to delete, and the sub_key is the key you ant to delete. I'm not on a Windows machine, so I can't test it right now.
OK,
Not A Pythonic Solution, but it works:
C:\Documents and Settings\admin>reg add "%REGISTRY_KEY%\Environment" /v AME /t
REG_EXPAND_SZ /d "%AME%" /f
#REG DELETE KeyName [/v ValueName | /ve | /va] [/f]
C:\Documents and Settings\admin>reg delete "%REGISTRY_KEY%\Environment" /v AME
/f
Der Vorgang wurde erfolgreich ausgeführt.
Success...
精彩评论