Search code examples
pythonpython-2.7pywin32

python RegDeleteKey error 5 access denied


I took the following python recipe from Activestate.org, then I simply added the method for deleting the key, however I getting error 5, access denied, and the key it's only a fake key which I have just created to try out the function . Here 's the code

## {{{ http://code.activestate.com/recipes/576860/ (r2)
import win32api
import win32con

def regquerysubkeys(handle, key, keylist=[]):

#get registry handle
    reghandle = win32api.RegOpenKeyEx(handle, key, 0, win32con.KEY_ALL_ACCESS)    
    try:
        i = 0
    #enumerates subkeys and recursively calls this function again
        while True:
            subkey = win32api.RegEnumKey(reghandle, i)
            #the following is the line I added myself
            win32api.RegDeleteKey(handle, key)


            i += 1
        #braintwister here ;-)
            regquerysubkeys(handle, key + subkey + "\\", keylist)
    except win32api.error as ex:
        #If no more subkeys can be found, we can append ourself
        if ex[0] == 259:
            keylist.append(key)
        #unexpected exception is raised
        else:
            raise
    finally:
    #do some cleanup and close the handle
        win32api.RegCloseKey(reghandle)
#returns the generated list
    print keylist

#call to the function
regquerysubkeys(win32con.HKEY_LOCAL_MACHINE, "SOFTWARE\\suga\\") 

Those are the errors I m getting in the console.

Traceback (most recent call last):
File "C:\EclipseWorkspaces\csse120\MMS-auto\test1.py", line 34, in <module>
regquerysubkeys(win32con.HKEY_LOCAL_MACHINE, "SOFTWARE\\suga\\")
File "C:\EclipseWorkspaces\csse120\MMS-auto\test1.py", line 14, in regquerysubkeys
win32api.RegDeleteKey(handle, key)
pywintypes.error: (5, 'RegDeleteKey', 'Access is denied.')

Can anyone help out with it?


Solution

  • Are you running 64-bit Windows 7 by any chance? There were some changes in the structure of the registry to account for running both 32-bit and 64-bit programs that require that you use different APIs for deletion. The RegDeleteKey Win32 API documentation mentions using RegDeleteKeyEx in some cases. The Win32 API is difficult to use reliably from one major version of Windows to the next. Unfortunately, pywin32 does its best to hide a number of the headaches, but it still requires that you really know the Win32 API and its caveats before you can effectively use it.