Python 检查是否存在注册表项
我在用python创建的安装程序中遇到了一个小问题。我有一个函数,它根据键的位置返回键的值Python 检查是否存在注册表项,python,installation,registry,winreg,Python,Installation,Registry,Winreg,我在用python创建的安装程序中遇到了一个小问题。我有一个函数,它根据键的位置返回键的值 def CheckRegistryKey(registryConnection, location, softwareName, keyName): ''' Check the windows registry and return the key value based on location and keyname ''' try: if registryConnect
def CheckRegistryKey(registryConnection, location, softwareName, keyName):
'''
Check the windows registry and return the key value based on location and keyname
'''
try:
if registryConnection == "machine":
aReg = ConnectRegistry(None,HKEY_LOCAL_MACHINE)
elif registryConnection == "user":
aReg = ConnectRegistry(None,HKEY_CURRENT_USER)
aKey = OpenKey(aReg, location)
except Exception, ex:
print ex
return False
try:
aSubKey=OpenKey(aKey,softwareName)
val=QueryValueEx(aSubKey, keyName)
return val
except EnvironmentError:
pass
如果该位置不存在,则会出现错误。我希望函数返回False
,这样如果位置不存在,我就可以运行软件安装程序,但它总是在异常中着陆
# check if the machine has .VC++ 2010 Redistributables and install it if needed
try:
hasRegistryKey = (edit_registry.CheckRegistryKey("machine", r"SOFTWARE\Wow6432Node\Microsoft\VisualStudio\10.0\VC\VCRedist", "x86", "Installed"))
if hasRegistryKey != False:
keyCheck = (edit_registry.CheckRegistryKey("machine", r"SOFTWARE\Wow6432Node\Microsoft\VisualStudio\10.0\VC\VCRedist", "x86", "Installed"))[0]
if keyCheck == 1:
print 'vc++ 2010 redist installed'
else:
print 'installing VC++ 2010 Redistributables'
os.system(productsExecutables + 'vcredist_x86.exe /q /norestart')
print 'VC++ 2010 Redistributables installed'
except Exception, ex:
print ex
运行代码时得到的异常是
'NoneType' object has no attribute '___getitem___'
我从def CheckRegistryKey
函数中得到的错误是
[Error 2] The system cannot find the file specified
我需要做的是检查注册表项或位置是否存在,如果不存在,则将其定向到可执行文件。感谢您的帮助
谢谢错误原因:
'NoneType' object has no attribute '___getitem___'
符合下列条件:
keyCheck = (edit_registry.CheckRegistryKey("machine", r"SOFTWARE\Wow6432Node\Microsoft\VisualStudio\10.0\VC\VCRedist", "x86", "Installed"))[0]
片段edit\u注册表。CheckRegistryKey(“machine”,r“SOFTWARE\Wow6432Node\Microsoft\VisualStudio\10.0\VC\vcredit”,“x86”,“Installed”)
返回无
这意味着您最终会:
keyCheck = (None)[0]
这就是你的错误所在。您正在尝试获取一个对象上没有的项
从CheckRegistryKey
函数返回None
的原因是,如果发生错误,您不会返回任何内容。当捕捉到环境错误时,需要返回False
:
try:
aSubKey=OpenKey(aKey,softwareName)
val=QueryValueEx(aSubKey, keyName)
return val
except EnvironmentError:
return False
我还将修改您的代码,以便您只调用一次CheckRegistryKey
:
registryKey = edit_registry.CheckRegistryKey("machine", r"SOFTWARE\Wow6432Node\Microsoft\VisualStudio\10.0\VC\VCRedist", "x86", "Installed")
if registryKey is not False:
keyCheck = registryKey[0]