簡體   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