Welcome, guest | Sign In | My Account | Store | Cart

A small function to get a value in windows registry from its key path and value name.

Note that recipe http://code.activestate.com/recipes/502268/ gives a more complete solution.

Python, 23 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import winreg

def regkey_value(path, name="", start_key = None):
    if isinstance(path, str):
        path = path.split("\\")
    if start_key is None:
        start_key = getattr(winreg, path[0])
        return regkey_value(path[1:], name, start_key)
    else:
        subkey = path.pop(0)
    with winreg.OpenKey(start_key, subkey) as handle:
        assert handle
        if path:
            return regkey_value(path, name, handle)
        else:
            desc, i = None, 0
            while not desc or desc[0] != name:
                desc = winreg.EnumValue(handle, i)
                i += 1
            return desc[1]

# example usage
bios_vendor = regkey_value(r"HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\BIOS", "BIOSVendor")

http://code.activestate.com/recipes/502268/ is ok but sometime you just want this small function.

1 comment

xiaomengy 5 years, 4 months ago  # | flag

I use windows XP and python 2.7.12,and i found two problem First: All four "winreg" should be replace as "_winreg" Second: The reg value should print and example reg value not found in Windows Xp