查询API时更新字典

时间:2018-03-02 14:57:16

标签: 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)
        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
 }
}

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

2 个答案:

答案 0 :(得分:1)

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

请注意,我无法对此进行测试,因为我不知道您正在使用哪种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 ) 

答案 1 :(得分:0)

原来非常简单,我只是需要休息一下才能看到它。只需要从类中启动列表和类中的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

输出具有可迭代数据结构的文件。