简体   繁体   English

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

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

I need to return the output from multiple functions inside a class in a dictionary format我需要从 class 中的多个函数以字典格式返回 output

I have tried using Python.我试过使用 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 How to print the results in json/ dict format in the console. I expect out put in {"VM": 45, "VPCs": 23, "Networks": 35} format But it print {} but that is wrong." “现在如何在控制台中以 json/dict 格式打印结果。我希望以 {"VM": 45, "VPCs": 23, "Networks": 35} 格式输出但它打印 {} 但这是错误的。”

For what I understood you need to actually define a constructor for your class.据我了解,您实际上需要为您的 class 定义一个构造函数。 Since it seems to be a simple dictionary we can inherit directly.由于它似乎是一个简单的字典,我们可以直接继承。

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

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

So when I do所以当我这样做的时候

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

And when I call the methods当我调用方法时

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

A complete simple example:一个完整的简单示例:

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()

Notice that I added the _ in front of _vm , _subnet and _vpc .请注意,我在_vm_subnet_vpc前面添加了_ This is mostly a naming convention (read more here and here ) used to declare something "private".这主要是一种命名约定( 在此处此处阅读更多内容),用于声明“私有”内容。 Since you only want to use those methods through runcompute() it fits the usage perfectly.由于您只想通过runcompute()使用这些方法,因此它非常适合使用。

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

相关问题 如何格式化python中的长行,其中函数调用返回多个输出并且我必须接收它们? - How to format the a long line in python where a function call returns multiple outputs and I have to receive them? 如何使用python扁平化和合并字典中的值? - How to flat and merge values in a dictionary using python? 是否可以使用Python中的单个function获得具有不同输出的多个按钮? - Is it possible to get multiple buttons with different outputs using a single function in Python? 使用字典将打印输出转换为python中的字符串 - Converting printed outputs using a dictionary to a string in python 如何使用 python 格式化字典中的所有值? - How to format all the values in dictionary using python? 如何在python中使用字符串格式打印字典 - How to print a dictionary using string format in python 如何创建从具有多个键的 Python 字典中输出特定键值的 Python 程序? - How to Create a Python Program that Outputs a Specific Key Value from a Python Dictionary that has Multiple Keys? 如何将多个时间戳合并到字典中? - how to merge multiple timestamps into a dictionary? 将函数的输出返回到字典 - Return outputs of a function to a dictionary Python字符串format()函数在语法中使用零引用字典 - Python string format() function using zero in the syntax to reference dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM