如何使用python以字典格式合并多功能输出?

问题描述 投票:0回答:1

我需要以字典格式返回类中多个函数的输出

我尝试使用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()

“ Now现在如何在控制台中以json / dict格式打印结果。我希望投入{“ VM”:45,“ VPC”:23,“网络”:35}格式但是它打印{},但这是错误的。“

python json dictionary
1个回答
1
投票

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

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。这主要是用于声明“私有”内容的命名约定(阅读更多herehere)。由于您只想通过runcompute()使用这些方法,因此非常适合使用。

© www.soinside.com 2019 - 2024. All rights reserved.