2012-11-08 93 views
1

我遇到了我在python中创建的安装程序中的一个小问题。我有一个函数根据它的位置返回一个键的值。检查一个注册表项是否存在python

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 

我需要做的是检查注册表项或位置存在,如果没有直接的关系它到一个可执行文件。任何帮助表示赞赏。

谢谢

回答

2

的原因错误:

'NoneType' object has no attribute '___getitem___' 

是在该行:

keyCheck = (edit_registry.CheckRegistryKey("machine", r"SOFTWARE\Wow6432Node\Microsoft\VisualStudio\10.0\VC\VCRedist", "x86", "Installed"))[0] 

片段edit_registry.CheckRegistryKey("machine", r"SOFTWARE\Wow6432Node\Microsoft\VisualStudio\10.0\VC\VCRedist", "x86", "Installed")将返回None

这意味着你结束了:

keyCheck = (None)[0] 

这就是扔你的错误。您正尝试在无对象的对象上获取项目。

CheckRegistryKey函数返回None的原因是,如果发生错误,则不返回任何内容。

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] 
+0

谢谢弥敦道,当你发现一个EnvironmentError你需要return False。这工作。我欠你一杯啤酒:) – floyd1510

+0

很高兴听到:) –

相关问题