Python winreg looping through sub-keys

前端 未结 6 1422
悲哀的现实
悲哀的现实 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条回答
  •  梦毁少年i
    2021-01-12 05:34

    Just want to add a perhaps more pythonic solution.

    from _winreg import *
    from contextlib import suppress
    import itertools
    
    def subkeys(path, hkey=HKEY_LOCAL_MACHINE, flags=0):
        with suppress(WindowsError), OpenKey(hkey, path, 0, KEY_READ|flags) as k:
            for i in itertools.count():
                yield EnumKey(k, i)
    

    You can now access the keys as expected

    for key in subkeys(r'path\to\your\key'):
        print key
    

    For python versions < 3.4 that lack suppress(), I recommend adding it to your project:

    from contextlib import contextmanager
    
    @contextmanager
    def suppress(*exceptions):
        try:
            yield
        except exceptions:
            pass
    

    Note: If you have trouble reading some values you might be reading from the wrong registry view. Pass KEY_WOW64_64KEY or KEY_WOW64_32KEY to the flags parameter). Using OpenKey() as context manager was introduced in python 2.6.

提交回复
热议问题