下面是我阅读注册表配置单元的代码。但我遇到了一个奇怪的事情。有时功能有效,有时不工作(返回错误代码2)。我注意到如果我使用regedit首先查看注册表项,然后关闭注册表,然后再次运行脚本,它可以工作。有没有人遇到过这样的错误?
以下是我的功能。
def _getMusicRegistryValue(self, keyName ):
value = ""
aKey = None
try:
HKLMKey = win32api.RegConnectRegistry(None, win32con.HKEY_LOCAL_MACHINE)
qqMusic = r"SOFTWARE\\Tencent\\QQMusic"
aKey = win32api.RegOpenKeyEx(HKLMKey, qqMusic)
#print 'aKey = ',aKey
(value,valueType) = win32api.RegQueryValueEx(aKey, keyName)
#installPath = "%sQQMusic.exe" %install
#print installPath
except Exception as data:
self.logger.error('*FAIL*: Exception happened when reading registry hive.Exception details: %s' %data)
errMsg = win32api.FormatMessage(data[0])
self.logger.error(errMsg)
#raise Exception("Read registry failed, QQMusic is not installed.")
finally:
if aKey is not None:
win32api.RegCloseKey(aKey)
#print 'close key'
if HKLMKey is not None:
win32api.RegCloseKey(HKLMKey)
return value
我试图关闭所有关键处理程序,但它仍然存在一些问题。
答案 0 :(得分:0)
错误2发生在他们没有密钥时,所以你应该检查脚本确实你正在寻找的密钥是否存在。
另外,虽然使用win32api是正确的,但我建议你使用_winreg(winthon in python 3),因为它在标准库中,不会让你添加win32api依赖。
如果应用程序QQMusic是x64机器中的x86应用程序,代码中可能存在错误,因为您还必须查看WoW64