Python 查询API时更新字典
我正在使用一个示例脚本查询API,我对他们的文档做了一些更改。我正在使用的函数如下所示Python 查询API时更新字典,python,Python,我正在使用一个示例脚本查询API,我对他们的文档做了一些更改。我正在使用的函数如下所示 def info(vm, depth=1): if hasattr(vm,'childEntity'): if depth > MAX_DEPTH: return vms = vm.childEntity for child in vms: info(child, depth+1)
def info(vm, depth=1):
if hasattr(vm,'childEntity'):
if depth > MAX_DEPTH:
return
vms = vm.childEntity
for child in vms:
info(child, depth+1)
return
summary = vm.summary
hardware = vm.config.hardware.device
macs = []
print("Name : {}".format(summary.config.name))
print("No of vCPUs : {}".format(summary.config.numCpu))
print("Memory (Mb) : {}".format(summary.config.memorySizeMB))
print("IP Address : {}".format(summary.guest.ipAddress))
for hw in hardware:
if hasattr(hw, 'macAddress'):
macs.append(hw.macAddress)
print("MAC Addresses :{}".format(mac_addresses))
def main():
si = None
host = creds.host
user = creds.user
password = creds.password
try:
si = SmartConnectNoSSL(host=host,
user=user,
pwd=password)
atexit.register(Disconnect, si)
except vim.fault.InvalidLogin:
raise SystemExit("Unable to connect to host "
"with supplied credentials.")
content = si.RetrieveContent()
for child in content.rootFolder.childEntity:
if hasattr(child, 'vmFolder'):
datacenter = child
vmfolder = datacenter.vmFolder
vmlist = vmfolder.childEntity
for vm in vmlist:
printvminfo(vm)
if __name__ == "__main__":
main()
Name : vm1
No of vCPUs : 2
Memory (Mb) : 10000
IP Address : 127.0.0.1
MAC Addresses :['00:01:22:33:4a:b5']
Name : vm2
No of vCPUs : 2
Memory (Mb) : 10000
IP Address : 127.0.0.2
MAC Addresses :['00:01:12:33:4g:b9', '40:51:21:38:4t:b5', '00:01:88:55:6y:z1']
Name : vm3
No of vCPUs : 2
Memory (Mb) : 10000
IP Address : 127.0.0.3
MAC Addresses :['00:50:56:83:d0:10']
这会打印出这样的内容
def info(vm, depth=1):
if hasattr(vm,'childEntity'):
if depth > MAX_DEPTH:
return
vms = vm.childEntity
for child in vms:
info(child, depth+1)
return
summary = vm.summary
hardware = vm.config.hardware.device
macs = []
print("Name : {}".format(summary.config.name))
print("No of vCPUs : {}".format(summary.config.numCpu))
print("Memory (Mb) : {}".format(summary.config.memorySizeMB))
print("IP Address : {}".format(summary.guest.ipAddress))
for hw in hardware:
if hasattr(hw, 'macAddress'):
macs.append(hw.macAddress)
print("MAC Addresses :{}".format(mac_addresses))
def main():
si = None
host = creds.host
user = creds.user
password = creds.password
try:
si = SmartConnectNoSSL(host=host,
user=user,
pwd=password)
atexit.register(Disconnect, si)
except vim.fault.InvalidLogin:
raise SystemExit("Unable to connect to host "
"with supplied credentials.")
content = si.RetrieveContent()
for child in content.rootFolder.childEntity:
if hasattr(child, 'vmFolder'):
datacenter = child
vmfolder = datacenter.vmFolder
vmlist = vmfolder.childEntity
for vm in vmlist:
printvminfo(vm)
if __name__ == "__main__":
main()
Name : vm1
No of vCPUs : 2
Memory (Mb) : 10000
IP Address : 127.0.0.1
MAC Addresses :['00:01:22:33:4a:b5']
Name : vm2
No of vCPUs : 2
Memory (Mb) : 10000
IP Address : 127.0.0.2
MAC Addresses :['00:01:12:33:4g:b9', '40:51:21:38:4t:b5', '00:01:88:55:6y:z1']
Name : vm3
No of vCPUs : 2
Memory (Mb) : 10000
IP Address : 127.0.0.3
MAC Addresses :['00:50:56:83:d0:10']
我正试图用
test['name'] = summary.config.name
test['vCPU'] = summary.config.numCpu
test['memory'] = summary.config.memorySizeMB
test['IP'] = summary.guest.ipAddress
test['mac'] = mac_addresses
print(test)
但是继续覆盖字典,以便一次只打印一个vm条目,而不是整个输出,因此我的输出当前为
{'vCPU': 2, 'IP': '127.0.0.1', 'mac': ['00:01:22:33:4a:b5'], 'name': 'vm1', 'memory': 10000}
{'vCPU': 2, 'IP': '127.0.0.2', 'mac': ['00:01:12:33:4g:b9', '40:51:21:38:4t:b5', '00:01:88:55:6y:z1'], 'name': 'vm2', 'memory': 10000}
{'vCPU': 2, 'IP': '127.0.0.3', 'mac': ['00:50:56:83:d0:10'], 'name': 'vm3', 'memory': 10000}
而我想
{
{
'vCPU': 2,
'IP': '127.0.0.1',
'mac': ['00:01:22:33:4a:b5'],
'name': 'vm1',
'memory': 10000
},
{
'vCPU': 2,
'IP': '127.0.0.2',
'mac': ['00:01:12:33:4g:b9', '40:51:21:38:4t:b5', '00:01:88:55:6y:z1'],
'name': 'vm2',
'memory': 10000
}
{
'vCPU': 2,
'IP': '127.0.0.3',
'mac': ['00:50:56:83:d0:10'],
'name': 'vm3',
'memory': 10000
}
}
是否有一个更有效的函数/循环可以使用?这里有一个想法,利用类来保存虚拟机的属性,您可以简单地重写类的
\uu str\uuu
定义,以便在打印类时可以输出您想要的任何内容
请记住,我无法测试这一点,因为我不知道您正在使用哪个API,而且您没有发布完整的代码集;所以这可能有点麻烦。您一定在某个地方创建了一个多次调用def info()
的循环,但我在这里没有看到
实际上,在多次调用def info()
的循环之前,您需要创建一个空列表/dict来保存在此过程中要创建的所有虚拟机对象
class VirtualMachine :
def __init__ (self, name, numCpu, mem, ip, mac):
self.name = name
self.vCPU = numCpu
self.memory = mem
self.IP = ip
self.mac = mac
def __str__ (self):
return """Name : {} \n
No of vCPUs : {} \n
Memory (Mb) : {} \n
IP Address : {} \n
MAC Addresses : {}
""".format(self.name, self.vCPU, self.memory, self.IP, self.mac)
def info(vm, depth=1):
if hasattr(vm,'childEntity'):
if depth > MAX_DEPTH:
return
vms = vm.childEntity
for child in vms:
info(child, depth+1)
return
summary = vm.summary
hardware = vm.config.hardware.device
macs = []
for hw in hardware:
if hasattr(hw, 'macAddress'):
macs.append(hw.macAddress)
v = VirtualMachine(summary.config.name, summary.config.numCPU, summary.config.memorySizeMB, summary.guest.ipAddress, mac_addresses)
# Here you should append `v` to some other dictionary that you defined before you entered the loop calling `info(vm, depth)`.
# Then you will have a full dictionary of all virtual machines you found in the API call loop.
print( v )
结果证明它非常简单,我只是需要休息一下。只需要在类外启动一个列表,在类中启动一个dict,将dict附加到循环中的列表中,并从另一个类打印它,这样就不会打印每个迭代
test_list = []
def printvminfo(vm, depth=1):
if hasattr(vm,'childEntity'):
if depth > MAX_DEPTH:
return
vms = vm.childEntity
for child in vms:
info(child, depth+1)
return
summary = vm.summary
hardware = vm.config.hardware.device
macs = []
test = {}
test['name'] = summary.config.name
test['vCPU'] = summary.config.numCpu
test['memory'] = summary.config.memorySizeMB
test['IP'] = summary.guest.ipAddress
for d in hardware:
if hasattr(d, 'macAddress'):
mac_addresses.append(d.macAddress)
test['mac'] = mac_addresses
test_list.append(test)
def get_list():
print(test_list)
正在运行
python script.py > file.txt
输出具有可编辑数据结构的文件。将其列为字典列表?感谢您的回复,我将尝试实现它。我已经添加了其余的代码,并且正在使用VMware API