简体   繁体   中英

Delete registry keys with subkeys using winreg on python

i am currently making a function that uses winreg to help me delete all the subkeys of a registry key. my current code

import winreg as wr

def delsub(k0, k1, k2=""):
    if k2 == "": current = k1
    else: current =  f'{k1}\\{k2}'

    openkey = wr.OpenKey(k0, current, 0, wr.KEY_ALL_ACCESS)
    infokey = wr.QueryInfoKey(openkey)
    for x in range(infokey[0]):
        subkey = wr.EnumKey(openkey, 0)

        try: wr.DeleteKey(openkey, subkey)
        except: delsub(k0, current, subkey)

    wr.DeleteKey(openkey,"")
    openkey.Close()

then i basically went to a random directory thing on regedit and created a key with 2 subkeys inside on the path Computer\HKEY_USERS\.DEFAULT\Control Panel\test . then i ran the function

delsub(wr.HKEY_USERS,r'.DEFAULT\Control Panel\test')

it gave me an error

Traceback (most recent call last):
  File "main.py", line 18, in <module>
    delsub(wr.HKEY_USERS,r'.DEFAULT\Control Panel\test')
  File "main.py", line 7, in delsub
    openkey = wr.OpenKey(k0, current, 0, wr.KEY_ALL_ACCESS)
PermissionError: [WinError 5] Access is denied

i tried giving it administrator access and same thing, so i really dont understand why

i get an error when opening the key though. the error doesn't explain much and i need some help also im knew to winreg so if i did something extremely stupid here please let me know

I have no idea why but it works now when i run it on administrator mode. Maybe yesterday I forgotten to give it admin access.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM