基于winreg模块删除注册表及其子项
说明:网络上很多代码运行都报错,经测试,底下代码运行一切正常
python 要求3.0版本以上
import winreg
def deleteSubkey(key0, key1, key2=""):
if key2=="":
currentkey = key1
else:
currentkey = key1+ "\\" +key2
open_key = winreg.OpenKey(key0, currentkey, 0, winreg.KEY_ALL_ACCESS)
infokey = winreg.QueryInfoKey(open_key)
for x in range(0, infokey[0]):
#NOTE:: This code is to delete the key and all subkeys.
# If you just want to walk through them, then
# you should pass x to EnumKey. subkey = winreg.EnumKey(open_key, x)
# Deleting the subkey will change the SubKey count used by EnumKey.
# We must always pass 0 to EnumKey so we
# always get back the new first SubKey.
subkey = winreg.EnumKey(open_key, 0)
try:
winreg.DeleteKey(open_key, subkey)
print("Removed %s\\%s " % (currentkey, subkey))
except:
deleteSubkey( key0, currentkey, subkey )
# no extra delete here since each call
#to deleteSubkey will try to delete itself when its empty.
winreg.DeleteKey(open_key,"")
open_key.Close()
print("Removed %s" % (currentkey))
return
if __name__ == '__main__':
# 删除注册表HKEY_CLASSES_ROOT\*\shell下的test目录及其子项
Parentkey = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'*\\shell', 0, winreg.KEY_ALL_ACCESS)
subkey = 'test'
deleteSubkey(Parentkey,subkey,'')
pycharm 开发工具请以管理员身份运行,否则程序运行可能报“PermissionError: [WinError 5] 拒绝访问”错误
或者将该python脚本打包成exe文件后以管理员身份运行,打包方法参考
pyinstaller 将python脚本打包成exe文件
若想用户输入待删除的项目 python脚本可以这样写
if __name__ == '__main__':
# 删除注册表HKEY_CLASSES_ROOT\*\shell下的test目录及其子项
Parentkey = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'*\\shell', 0, winreg.KEY_ALL_ACCESS)
subkey = input('please input the name of the project which you want to delete : ')
# subkey = 'test'
try:
deleteSubkey(Parentkey,subkey,'')
except Exception as e:
print(e)
os.system('pause') # 可解决Python打包生成的exe运行完直接退出的问题