A helper function to remove Windows registry key recursively
The default register function of Python(2.6.x) can’t delete a Windows registry key recursively, an exception(Access is denied) will be thrown if you try to delete a key with sub-keys , below is a wrapper which is easy-to-use, you could use it to delete a key and its sub-keys:
import _winreg def traverse(root, key, list): hKey = _winreg.OpenKey(root, key); try: i = 0 while 1: strFullSubKey = ""; try: strSubKey = _winreg.EnumKey(hKey, i) strFullSubKey = key + "\\" + strSubKey; except WindowsError: hKey.Close(); return; traverse(root, strFullSubKey, list); #print strFullSubKey; list.append(strFullSubKey); i += 1 except WindowsError: print hKey.Close(); def reg_delete_key(root, key): global list; list = list(); traverse(root, key, list); for item in list: _winreg.DeleteKey(root, item); #print item; _winreg.DeleteKey(root, key); # Example: reg_delete_key(_winreg.HKEY_CURRENT_USER, r"Software\charry.org");
Keyword: Python, RegDeleteKey, 注册表, 删除
[ad]
Brown Belt Said on November 26th, 2010 at 8:42 pm quote
Thank you for a fantastic post. I enjoyed it.