2

I am writing this script to pull performance data from vcenter using python. If a counter does not exists for a guest, the script exists/breaks.

How would I check first that if the counter exists for a vm than assign the value:

Here is the script:

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()

This is the error:

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

3 Answers3

4

You can use in like this:

if "virtualDisk.totalReadLatency" in counterValues:
    doSomething()
else:
    pass
k-nut
  • 3,447
  • 2
  • 18
  • 28
3

You can use a try/except block (according to the Zen of Python, it's better to ask for forgiveness than permission ;-)

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

This way you can wrap all key-lookups into one try (better, refactor it to a single function).

tamasgal
  • 24,826
  • 18
  • 96
  • 135
1

Dictionaries have the .get() method, if you want to substitute a default value that's used if the key doesn't exist:

ReadLatency = counterValues.get('virtualDisk.totalReadLatency', 0)  # 0 is default
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79