Skip to main content
 首页 » 编程设计

python之查询 API 时更新字典

2025年01月19日10exmyth

我正在使用示例脚本查询 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) 
        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 
 } 
} 

我可以使用更高效的函数/循环吗?

请您参考如下方法:

这是一个想法,利用一个类来保存虚拟机的属性,您可以简单地覆盖该类的 __str__ 定义,这样您就可以在打印时输出任何您想要的内容类(class)。

请记住,我无法对此进行测试,因为我不知道您使用的是哪个 API,而且您没有发布完整的代码集;所以这可能有点问题。您一定是在某处创建了一个多次调用 def info() 的循环,但我在这里没有看到。

本质上,在多次调用 def info() 的循环之前,您需要创建一个空列表/字典来保存您将在此过程中创建的所有虚拟机对象。

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 )