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

Most of the time I just want to either read or write one value to the registry. Here are two functions: ReadRegistryValue and WriteRegistryValue plus a few helpers.

Python, 71 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
Simplest Windows Registry I/0
"""
import win32api
import win32con

def ReadRegistryValue(hiveKey, key, name=""):
    """ Read one value from Windows registry. If 'name' is empty string, reads default value."""
    data = typeId = None
    try:
        keyHandle = win32api.RegOpenKeyEx(hiveKey, key, 0, win32con.KEY_ALL_ACCESS)
        data, typeId = win32api.RegQueryValueEx(keyHandle, name)
        win32api.RegCloseKey(keyHandle)
    except Exception, e:
        print "ReadRegistryValue failed:", hiveKey, key, name, e
    return data, typeId

def WriteRegistryValue(hiveKey, key, name, data, typeId=win32con.REG_SZ):
    """ Write one value to Windows registry. If 'name' is empty string, writes default value.
        Creates subkeys as necessary"""
    try:
        keyHandle = OpenRegistryKey(hiveKey, key)
        win32api.RegSetValueEx(keyHandle, name, 0, typeId, data)
        win32api.RegCloseKey(keyHandle)
    except Exception, e:
        print "WriteRegistryValue failed:", hiveKey, name, e

def OpenRegistryKey(hiveKey, key):
    """ Opens a keyHandle for hiveKey and key, creating subkeys as necessary """
    keyHandle = None
    try:
        curKey = ""
        keyItems = key.split('\\')
        for subKey in keyItems:
            if curKey:
                curKey = curKey + "\\" + subKey
            else:
                curKey = subKey
            keyHandle = win32api.RegCreateKey(hiveKey, curKey)
    except Exception, e:
        keyHandle = None
        print "OpenRegistryKey failed:", hiveKey, key, e
    return keyHandle

def DeleteRegistryKey(hiveKey, key):
    """ Deletes a registry key -- must be a leaf key or call fails """
    try:
        result = win32api.RegDeleteKey(hiveKey, key)
        return result
    except Exception, e:
        print "DeleteRegistryKey failed:", hiveKey, key, e
    return None

def TestRegistryWriteRead(hiveKey, key, name, data, typeId):
    WriteRegistryValue(hiveKey, key, name, data, typeId)
    outputData, outputTypeId = ReadRegistryValue(hiveKey, key, name)
    status = "OK"
    if (outputData != data or outputTypeId != typeId):
        status = "FAILED"
    print "%s -- %d %s %s -- input: %s %s  output: %s %s" % \
        (status, hiveKey, key, name, str(data), str(typeId), str(outputData), str(outputTypeId))

def Test():
    TestRegistryWriteRead(win32con.HKEY_LOCAL_MACHINE, "Software\\AAAAA", "", "this is a default value", win32con.REG_SZ)
    TestRegistryWriteRead(win32con.HKEY_LOCAL_MACHINE, "Software\\AAAAA", "Data-SZ", "this is a string", win32con.REG_SZ)
    TestRegistryWriteRead(win32con.HKEY_LOCAL_MACHINE, "Software\\AAAAA", "Data-BINARY", '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09', win32con.REG_BINARY)
    TestRegistryWriteRead(win32con.HKEY_LOCAL_MACHINE, "Software\\AAAAA", "Data-DWORD", 0x01234567, win32con.REG_DWORD)
    DeleteRegistryKey(win32con.HKEY_LOCAL_MACHINE, "Software\\AAAAA")
    
if __name__ == "__main__":
    Test()

All I want is a read function and a write function that handle the five components of a registry entry and use them simply and directly. I also want to glance at the internals of the code and know what's going at the Windows API level without winreg or various Python indirections in the way.

There are already several fine, thorough-going recipes here that wrap the Windows registry API and make it more regular and pythonic. I admire all the work that has been done. However, these are more than I need.

Note: These calls are only tested for string, dword and binary registry values.

1 comment

Jorge Besada 13 years, 11 months ago  # | flag

Nice, I can use it. Can you add sample code to connect to a remote machine? Thanks!