繁体   English   中英

如何使用 python 以字典格式合并多个 function 的输出?

[英]How to merge outputs of multiple function in a dictionary format using python?

我需要从 class 中的多个函数以字典格式返回 output

我试过使用 Python。

dict={}
class Compute():

    def vm(self):
        for obj in data['profile']:
            for region_name in obj['region']:
                conn = boto3.resource('ec2', aws_access_key_id=obj["access_key"], aws_secret_access_key=obj["secret_key"],
                    region_name=region_name)
                instances = conn.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running', 'stopped']}])
                for instance in instances:
                    instance_count.append(instance)
                    instanceCount = str(len(instance_count))
        dict['VM'] = len(instance_count)


    #Subnet
    def subnet(self):
        subnet_count=0
        for obj in data['profile']:
            for region_name in obj['region']:
                conn = boto3.client('ec2', aws_access_key_id=obj["access_key"], aws_secret_access_key=obj["secret_key"],
                                  region_name=region_name)
                subnet = conn.describe_subnets()
                #print('subnet'+ ' '+ region_name + ' ' +str(len(subnet['Subnets'])))
                subSize = len(subnet['Subnets'])
                subnet_count+=subSize
        dict['Networks'] = subnet_count

    #VPCS
    def vpc(self):
            for obj in data['profile']:
                for region_name in obj['region']:
                    conn = boto3.resource('ec2', aws_access_key_id=obj["access_key"], aws_secret_access_key=obj["secret_key"],
                      region_name=region_name)
                    vpcs = conn.vpcs.filter()
                    for vpc in vpcs:
                        vpc_count.append(vpc)
                        vpcCount = str(len(vpc_count))

            dict['VPCs'] = len(vpc_count)

     print(dict)    #this only prints {}   


    def runcompute(self):
        if __name__ == '__main__':
            Thread(target=self.vm).start()
            Thread(target=self.subnet).start()
        Thread(target=self.vpc).start()

if __name__ == '__main__':
    try:
        if sys.argv[1]=='compute':
             run = Compute()
             run.runcompute()

“现在如何在控制台中以 json/dict 格式打印结果。我希望以 {"VM": 45, "VPCs": 23, "Networks": 35} 格式输出但它打印 {} 但这是错误的。”

据我了解,您实际上需要为您的 class 定义一个构造函数。 由于它似乎是一个简单的字典,我们可以直接继承。

class Compute(dict):
     def __init__(self): 
         super().__init__(self) 

     def my_method(self): # equivalent of your methods in your class
         self["foo"] = 1

所以当我这样做的时候

run = Compute()
print(run)
>> {} # we just created the object

当我调用方法时

run.my_method()
print(run)
>> { 'foo': 1 }  # and here we are

一个完整的简单示例:

import sys
from threading import Thread

class Compute(dict):
    def __init__(self):
        super().__init__(self)  # short version
        # super(Compute, self).__init__(self)  # long version

    def _vm(self):
        instance_count = [0] * 45  # do your stuff
        self["VM"] = len(instance_count)

    def _subnet(self):
        subnet_count = 35  # do your stuff
        self["Networks"] = subnet_count

    def _vpc(self):
        vpc_count = [0] * 23  # do your stuff
        self["VPCs"] = len(vpc_count)

    def runcompute(self):
        # Create the threads
        vm = Thread(target=self._vm)
        subnet = Thread(target=self._subnet)
        vpc = Thread(target=self._vpc)
        # Actually start the threads
        vm.start()
        subnet.start()
        vpc.start()

        print(self)  # If you really want to print the result here

if __name__ == "__main__":
    if sys.argv[1] == "compute":
        run = Compute()
        run.runcompute()

请注意,我在_vm_subnet_vpc前面添加了_ 这主要是一种命名约定( 在此处此处阅读更多内容),用于声明“私有”内容。 由于您只想通过runcompute()使用这些方法,因此它非常适合使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM