Python winreg looping through sub-keys

前端 未结 6 1385
悲哀的现实
悲哀的现实 2021-01-12 05:16

I\'m able to successfully retrieve the 5 sub-keys from my windows 7 machine registry hive \"HKEY_LOCAL_MACHINE\" with the code below.

from _winreg import *

         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-12 05:37

    this is just an improvement on @sparrowt's answer. His answer failed when I tried it, but think it was on the right track. This will give tree below keypath. Sorry for changing some variable and method names in rewrite, but just trying to post this quick. In my code, I put hkey as global variable bc I expect to only be working with one hkey at a time.

    import winreg
    import itertools
    hkey = winreg.HKEY_LOCAL_MACHINE
    def list_subkeys(path, hkey_set=None):
        global hkey
        if not hkey_set:
            hkey_set = hkey
        try:
            registry_key = winreg.OpenKey(hkey_set, path, 0, winreg.KEY_READ)
            for i in itertools.count():
                yield winreg.EnumKey(registry_key, i)
            winreg.CloseKey(registry_key)
        except Exception as ex:
            if str(ex) != '[WinError 259] No more data is available':
                print(str(ex))
            try:
                winreg.CloseKey(registry_key)
            except:
                pass
            return []
    
    def traverse_registry_tree(keypath, levels=None, hkey_set=None):
        global hkey
        if not levels:
            levels = []
        if not hkey_set:
            hkey_set = hkey
        subkeys = list(list_subkeys(keypath, hkey_set))
        for subkeyname in subkeys:
            subkeypath = "%s\\%s" % (keypath, subkeyname)
            levels.append(subkeypath)
            levels.extend([r for r in traverse_registry_tree(subkeypath, levels, hkey_set) if r not in levels])
        del subkeys
        return levels
    

提交回复
热议问题