Sunday, October 12, 2008

Python - Windows registry access (pyregistry)

The python module which is given below - pyregistry is a wrapper around _winreg module. It greatly simplifies registry access, which is more complicated if _winreg is used directly. It implements readSubKeys, readValues and pathExists functions.
readSubKeys - Returns an array of all the sub keys, -1 if the registry path doesnt exist.
readValues - Returns a hash/dictionary of all the values under the key, -1 if the registry path doesnt exist.
pathExists - Returns True if the registry path exists, False otherwise
The docstrings explains the usage of these functions.
from _winreg import *
mapping = { "HKLM":HKEY_LOCAL_MACHINE, "HKCU":HKEY_CURRENT_USER, "HKU":HKEY_USERS }

def readSubKeys(hkey, regPath):
    if not pathExists(hkey, regPath):
        return -1
    reg = OpenKey(mapping[hkey], regPath)
    subKeys = []
    noOfSubkeys = QueryInfoKey(reg)[0]
    for i in range(0, noOfSubkeys):
        subKeys.append(EnumKey(reg, i))
    CloseKey(reg)
    return subKeys

def readValues(hkey, regPath):
    if not pathExists(hkey, regPath):
        return -1
    reg = OpenKey(mapping[hkey], regPath)
    values = {}
    noOfValues = QueryInfoKey(reg)[1]
    for i in range(0, noOfValues):
        values[EnumValue(reg, i)[0]] = EnumValue(reg, i)[1]
    CloseKey(reg)
    return values

def pathExists(hkey, regPath):
    try:
        reg = OpenKey(mapping[hkey], regPath)
    except WindowsError:
        return False
    CloseKey(reg)
    return True
~m.a.v.e.r.i.c.k

3 comments:

Anonymous said...

Hey this is exactly what i was looking for. Super cool, thanks!

Anonymous said...

Thank you very much!

ascii said...

Very helpful !