1

我在 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

我需要做的是检查注册表项或位置是否存在,如果不将其定向到可执行文件。任何帮助表示赞赏。

谢谢

4

1 回答 1

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]

这就是引发您的错误的原因。您正试图在无对象的对象上获取项目。

None您从函数中返回的原因CheckRegistryKey是,如果发生错误,您不会返回任何内容。return False当你抓住一个时你需要EnvironmentError

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]
于 2012-11-08T06:38:12.590 回答