我正在尝试根据vmware快速统计计算%cpu利用率。问题是快速统计数据不能为guest提供%cpu利用率,所以我必须找到一种方法来计算它。我在字典中有主机cpu速度值对存储,如下所示:
{'host-594':2194,'host-10249':2194,'host-6484':2194,'host-6486':1861,'host-6480':2194,'host-6482': 2194,'host-699':2194,'host-6364':1861,'host-500':2194,'host-17424':2194,'host-502':2194,'host-17426':2194, 'host-17420':2194,'host-17422':2194,'host-17428':2194,'host-1805':2665,'host-4360':1862,'host-858':2194,'host -1067':2194,'host-1065':2194,'host-4162':1861,'host-1063':2194,'host-1061':2194,'host-17396':2194,'host-3394 ':2132,'host-1069':2194,'host-5565':2132}
然后,
我可以按如下方式获取Used_CpuMhz,Num_vCpu和host_id(guest虚拟机属于):
properties = ["name",
"summary.quickStats.overallCpuUsage",
"summary.runtime.host",
"config.hardware.numCPU"]
results = s._retrieve_properties_traversal(property_names=properties, obj_type=MORTypes.VirtualMachine)
for item in results:
for r in item.PropSet:
if r.Name == "name" :
name = r.Val
Used_CpuMhz = 0
Num_vCpu = 0
host_id = none
for p in item.PropSet:
if p.Name=="summary.quickStats.overallCpuUsage":
Used_CpuMhz=p.Val
if p.Name=="config.hardware.numCPU":
Num_vCpu=p.Val
if p.Name=="summary.runtime.host":
host_id=p.Val
#here I have to read myDict() where I need get the value pair
#for host_id in myDict. I need to scan myDict and if I see host_id
#in there, I need to assign the value to speed variable in here
%CPU= Used_CpuMhz/(Num_vCpu*speed)
给定此值:{host-594': 2194}
,如果if语句中的host_id为“host-594”,则速度应为2194.因此,对于每个guest虚拟机,我需要扫描myDict并找到匹配主机的cpu速度。有人可以提供一些有关如何做到这一点的见解吗?
我修改了以下代码:
if p.Name=="summary.quickStats.overallCpuUsage":
Used_CpuMhz=p.Val
if p.Name=="config.hardware.numCPU":
Num_vCpu=p.Val
if p.Name=="summary.runtime.host":
host_id=p.Val
if host_id in myDict:
cpu_speed = myDict[host_id]
if Used_CpuMhz >0 and Num_vCpu >0:
Percent_Cpu_Used=(float(Used_CpuMhz)/(float(Num_vCpu)*float(cpu_speed)))*100
我收到此错误:
Traceback (most recent call last):
File "host.py", line 138, in <module>
Percent_Cpu_Used=(float(Used_CpuMhz)/(float(Num_vCpu)*float(cpu_speed)))*100
ZeroDivisionError: float division
答案 0 :(得分:1)
if host_id in myDict:
speed = myDict[host_id]
一种等效的方法:
if host_id in myDict.keys():
speed = myDict[host_id]
答案 1 :(得分:1)
如果要在字典中找不到主机时指定要使用的默认值:
speed = myDict.get(host_id, 12345) # Default of 12345
当然,如果您确实希望所有主机都在字典中,那么只需查看它:
speed = myDict[host_id]