Deleting a Windows Registry Value with Python

oz123 picture oz123 · Jan 11, 2011 · Viewed 7.9k times · Source

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

Answer

jfs picture jfs · Jan 11, 2011

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')