Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

Python code to read registry

from _winreg import *

"""print r"*** Reading from SOFTWAREMicrosoftWindowsCurrentVersionRun ***" """
aReg = ConnectRegistry(None,HKEY_LOCAL_MACHINE)

aKey = OpenKey(aReg, r"SOFTWAREMicrosoftWindowsCurrentVersionUninstall")
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 HKLMSOFTWAREMicrosoftWindowsCurrentVersionUninstall 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

from _winreg import *

aKey = r"SOFTWAREMicrosoftWindowsCurrentVersionUninstall"
aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)

print(r"*** Reading from %s ***" % aKey)

aKey = OpenKey(aReg, aKey)
for i in range(1024):
    try:
        asubkey_name = EnumKey(aKey, i)
        asubkey = OpenKey(aKey, asubkey_name)
        val = QueryValueEx(asubkey, "DisplayName")
        print(val)
    except EnvironmentError:
        break

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...