For example, I want to remove the whole path HKCU\Software\Classes\ms-settings
and its subkeys from the registry.
In batch, it would be as simple as:
REG DELETE "HKCU\Software\Classes\ms-settings" /F
In python, I tried using winreg
:
import winreg
HKCU = winreg.HKEY_CURRENT_USER
REG_PATH = r'Software\Classes\ms-settings'
winreg.DeleteKey(HKCU, REG_PATH)
but it returns WinError 5
PermissionError: [WinError 5] access is denied
Edit: After I've done some research, I realized that in this case, access is denied
has nothing to do with admin rights, but its subkeys aren't deleted, so it returns an error. I tried using loops instead:
#Delete registry keys using recursion
import winreg
HKCU = winreg.HKEY_CURRENT_USER
REG_PATH = r'Software\Classes\ms-settings\shell\open\command'
#Delete registry keys
hKey = winreg.CreateKey(HKCU, REG_PATH)
winreg.DeleteValue(hKey, 'DelegateExecute')
#Delete registry paths
key = REG_PATH.split('\\')
for x in range(6,2,-1):
path = '\\'.join(key[:x])
winreg.DeleteKey(HKCU, path)
It works, but it's not a practical method. How can you know the name of all subkeys in a key? Is there no built-in function for this in python? Or am I just reinventing the wheel?