Python winreg looping through sub-keys

user1982218 picture user1982218 · Jan 16, 2013 · Viewed 14.1k times · Source

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 *

try:
    i = 0
    while True:
        subkey = EnumKey(HKEY_LOCAL_MACHINE, i)
        print subkey
        i += 1
except WindowsError:
    pass

My question is, how do I then enumerate the keys under those? I want to end up listing all the keys in the SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Signatures\Unmanaged folder but I can't figure out how to step my way down there.

In response to the first comment, I ran this code on my machine and while it didn't error out, it didn't produce results.

from _winreg import *

aReg = ConnectRegistry(None,HKEY_LOCAL_MACHINE)
aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Signatures\Unmanaged")
for i in range(1024):
    try:
        keyname = EnumKey(aKey, i)
        asubkey = OpenKey(aKey, keyname)
        val = QueryValueEx(asubkey, "Description")
        print val
    except WindowsError:
        break

A regedit or reg query shows 6 values in that folder but I can't get a python script to show me those six.

Answer

wihlke picture wihlke · Mar 20, 2019

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.