Search code examples
pythonregistry

Python code to read registry


from _winreg import *

"""print r"*** Reading from SOFTWARE\Microsoft\Windows\CurrentVersion\Run ***" """
aReg = ConnectRegistry(None,HKEY_LOCAL_MACHINE)

aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall")
for i in range(1024):
    try:
        asubkey=EnumKey(aKey,i)
        val=QueryValueEx(asubkey, "DisplayName")
        print val
    except EnvironmentError:
        break

Could anyone please correct the error...i just want to display the "DisplayName" within the subkeys of the key the HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall This is the error i get..

Traceback (most recent call last):
  File "C:/Python25/ReadRegistry", line 10, in <module>
    val=QueryValueEx(asubkey, "DisplayName")
TypeError: The object is not a PyHKEY object

Solution

  • Documentation says that EnumKey returns string with key's name. You have to explicitly open it with winreg.OpenKey function. I've fixed your code snippet:

    import winreg
    aReg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
    print(r"*** Reading from %s ***" % aKey)
    
    aKey = winreg.OpenKey(aReg, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall')
    for i in range(1024):
        try:
            aValue_name = winreg.EnumKey(aKey, i)
            oKey = winreg.OpenKey(aKey, aValue_name)
            sValue = winreg.QueryValueEx(oKey, "DisplayName")
            print(sValue)
        except EnvironmentError:
            break
    

    Please note, that not every key has "DisplayName" value available.