简体   繁体   中英

How to return the whole list from a python function

I have a small script as follows:

import boto3
ACCESS_KEY= "XXXXXXXXXXXXX"
SECRET_KEY= "XXXXXXXXXXXX"
regions = ['us-east-1','us-west-1','us-west-2','eu-west-1','sa-east-1','ap-southeast-1','ap-southeast-2','ap-northeast-1']
for region in regions:
  client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
  addresses_dict = client.describe_addresses()
  for eip_dict in addresses_dict['Addresses']:
     print eip_dict['PublicIp']

This code works fine and prints the list of all EIP's from ALL region, now i am trying to use the above code in my another script using functions as :

def gather_public_ip():
   ACCESS_KEY = config.get('aws','access_key')
   SECRET_KEY = config.get('aws','secret_key')
   regions = ['us-east-1','us-west-1','us-west-2','eu-west-1','sa-east-1','ap-southeast-1','ap-southeast-2','ap-northeast-1']
   all_EIP = []
   for region in regions:
      client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
      addresses_dict = client.describe_addresses()
      for eip_dict in addresses_dict['Addresses']:
          print eip_dict['PublicIp']
          all_EIP.append(eip_dict['PublicIp'])
          return all_EIP

But this breaks after 1st iteration only (it just prints one IP) and doesn't return the whole list to caller , i am calling the above function from __main__ as follows :

       net_range =  gather_public_ip()
       r = s.run(net_range)
       s.save()   # save

Basically i want to pass the list of returned ip's to run() . Can someone help me ?

You return your all_EIP in the first iteration of the nested for loop. Indent the return so it gets executed after the outer for and you should have all of what is supposed to get appended.

def gather_public_ip():
   ACCESS_KEY = config.get('aws','access_key')
   SECRET_KEY = config.get('aws','secret_key')
   regions = ['us-east-1','us-west-1','us-west-2','eu-west-1','sa-east-1','ap-southeast-1','ap-southeast-2','ap-northeast-1']
   all_EIP = []
   for region in regions:
      client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
      addresses_dict = client.describe_addresses()
      for eip_dict in addresses_dict['Addresses']:
          print eip_dict['PublicIp']
          all_EIP.append(eip_dict['PublicIp'])
   return all_EIP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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