从python对象编辑键 - 获取TypeError:迭代非序列

时间:2015-02-24 15:32:12

标签: python python-2.7

当我打印出变量

print myOptions

我得到了

 {'verbose': False,
'number': '1',
'asgMaxSize': '?dev = 2 | ?qa = 2 | ? prd = 8',
'availabilityZone': 'us-east-1a,us-east-1e',
'securityGroups': ['bouncebox-member', 'bouncebox-member'],
'\
    instanceType': '?dev =  m3.medium | ?qa = m3.medium | ?prd = m3.medium',
'runcommon': False,
'zone': 'inpwrd.net',
'bubblewrapp': False,
'healthCheckTarget': 'HTTP:8080/:NAME:/api/health-check',
'environment': 'dev',
'application': 'tint',
'nscustomerdata': None,
'ami': 'ami-8a5d81e2',
'userData': 'defaultUserData.txt',
'outputFile': None,
'description': 'tint - replacement thumbscraper stack',
'desiredCapacity': '1',
'securityPorts': 'httpPort8080,sshPort',
'instanceProfile': 'default-:ENV:1',
'elbListeners': 'http8080',
'name': 'tint',
'blockDeviceMap': 'Empty',
'instanceMonitoring': 'false',
'asgMinSize': '1',
'keyname': None,
'alarms': 'diskspace,memory,tint'}

(为了便于阅读而增加了换行符)

所以它看起来像一个键/值对我。我想像这样迭代它:

for key in myOptions:
    if key == "instanceProfile":
        myOptions.value = myOptions.value.replace(":ENV:", "dev")

但是当我运行代码时,我得到"TypeError: iteration over non-sequence"

那么,我如何确定对象的类型以及如何遍历那里的键/值对(字典?)?

我正在使用python版本2.7.8,如果这会产生影响。

当我打印出“print myOptions。 class ”时,我会收到“optparse.Values”

构建myOptions是

from optparse import OptionParser
_opt = OptionParser("%prog [options] configfiles...")

_opt.add_option("-v", "--verbose", ...)
_opt.add_option("-r", "--runcommon", ...)
.... a bunch of _opt.add_option

import shlex
def parse(filename, defaults):
    myopt, args = _opt.parse_args(shlex.split(open(filename).read()), defaults)
    return myopt

if __name__ == "__main__":
    import sys

    myOptions, args = _opt.parse_args()
    myOptions = parse("default.ini", myOptions)
    for arg in args:
       myOptions = parse(arg, myOptions)

    myOptions, args = _opt.parse_args(values = myOptions)

    argConfigurationName = args[-1]
    if (myOptions.name == None):
        myOptions.name = argConfigurationName

    if myOptions.verbose == True:
        print "Configuration Variables"
        for name in _opt.defaults:
            print "\t", name, "=", getattr(myOptions, name)

0 个答案:

没有答案