[英]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 : 这段代码可以正常工作并打印来自ALL区域的所有EIP的列表,现在我正尝试在其他脚本中使用上述代码,其功能如下:
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 : 但这仅在第一次迭代后中断(它仅打印一个IP),并且没有将整个列表返回给调用者 ,我从
__main__
调用上述函数,如下所示:
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()
. 基本上我想将返回的IP列表传递给
run()
。 Can someone help me ? 有人能帮我吗 ?
You return your all_EIP
in the first iteration of the nested for loop. 您在嵌套的for循环的第一个迭代中返回
all_EIP
。 Indent the return so it gets executed after the outer for and you should have all of what is supposed to get appended. 缩进返回值,以便它在外部for之后执行,您应该拥有应该附加的所有内容。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.