2012-11-08 115 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

很高興聽到:) –

相關問題