如何检查python中是否存在值

how do check if a value exists in python

本问题已经有最佳答案,请猛点这里访问。

我编写这个脚本是为了使用python从vCenter中提取性能数据。如果来宾不存在计数器,则脚本存在/中断。

我如何首先检查如果一个vm的计数器存在,那么分配该值:

下面是脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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()

这是错误:

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

您可以这样使用in

1
2
3
4
if"virtualDisk.totalReadLatency" in counterValues:
    doSomething()
else:
    pass


你可以使用一个try/except块(根据python的禅,请求宽恕比请求许可要好;-)

1
2
3
4
try:
     # your lookup
except KeyError:
     # your error handling

这样,您就可以将所有的键查找打包成一个try(更好的做法是将其重构为一个函数)。


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

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