如何检查python中是否存在值

时间:2014-11-20 15:43:58

标签: python

我正在编写此脚本以使用python从vcenter中提取性能数据。如果guest虚拟机不存在计数器,则脚本存在/中断。

如果vm的计数器存在而不是分配值,我将如何检查:

这是脚本:

for vmpath in vmlist:
#Get the current performance manager object (it changes, so we can’t just instatiate it once)
    pm = server.get_performance_manager()
    #Get an actual VM object from the path
    vm = server.get_vm_by_path(vmpath)
    #Get the managed object reference for the VM, because the performance manager only accepts MoRefs
    mor = vm._mor
    #Get all the counters and their current values for that VM.
    counterValues = pm.get_entity_counters(mor)
    #Do some quick math on the values.
    #They come to us in a convienent dictionary form.
    #Values are descrobed here: http://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/virtual_disk_counters.html
    if InitMyVariable.my_variable is None:
    cpu_usage=counterValues['cpu.usage']
    cpu_ready=counterValues['cpu.ready']
    total_memory=counterValues['mem.granted']
    memory_used=counterValues['mem.consumed']
    Memory_usage=counterValues['mem.usage']
    Memory_ballooned=counterValues['mem.vmmemctl']
    Memory_swapped=counterValues['mem.swapped']
    ReadLatency = counterValues['virtualDisk.totalReadLatency']
    WriteLatency = counterValues['virtualDisk.totalWriteLatency']

    #print them out.
    print "VM Name",vm.get_property('name')
    print "% CPU",cpu_usage
    print "CPU Ready",cpu_ready
    print "Total Memory",memory_used
    print "% Memory Used",Memory_usage
    print "Memory Ballooned",Memory_ballooned
    print "Memory Swapped",Memory_swapped
    print "Disk Read Latency",ReadLatency
    print "Disk Write Latency",WriteLatency
    print "——-"

server.disconnect()

这是错误:

Traceback (most recent call last):
  File "guest_perf.py", line 38, in <module>
    ReadLatency = counterValues['virtualDisk.totalReadLatency']
KeyError: 'virtualDisk.totalReadLatency'

3 个答案:

答案 0 :(得分:3)

你可以使用try / except块(根据Python的Zen,最好是请求宽恕而不是许可; - )

try:
     # your lookup
except KeyError:
     # your error handling

这样你就可以将所有的键查找包装成一个try(更好的是,将它重构为一个函数)。

答案 1 :(得分:3)

您可以像这样使用in

if "virtualDisk.totalReadLatency" in counterValues:
    doSomething()
else:
    pass

答案 2 :(得分:1)

字典采用.get()方法,如果您想要替换在密钥不存在时使用的默认值:

ReadLatency = counterValues.get('virtualDisk.totalReadLatency', 0)  # 0 is default