Oli*_*ver 6 amazon-ec2 python-3.x boto3
在 boto3 中有一个函数:
ec2.instances.filter()
Run Code Online (Sandbox Code Playgroud)
文档:http : //boto3.readthedocs.org/en/latest/reference/services/ec2.html#instance
假设它返回一个我希望的列表(ec2.Instance)...
当我尝试打印退货时,我得到了这个:
ec2.instancesCollection(ec2.ServiceResource(), ec2.Instance)
Run Code Online (Sandbox Code Playgroud)
我尝试搜索任何提及 ec2.instanceCollection 的内容,但我发现的唯一内容与 ruby 类似。
我想遍历这个 instanceCollection 以便我可以看到它有多大,存在哪些机器以及类似的东西。问题是我不知道它是如何工作的,并且当它为空时迭代根本不起作用(它会引发错误)
该filter方法不返回列表,而是返回一个可迭代对象。这基本上是一个 Python 生成器,它将以有效的方式按需生成所需的结果。
您可以在循环中使用此迭代器,如下所示:
for instance in ec2.instances.filter():
# do something with instance
Run Code Online (Sandbox Code Playgroud)
或者,如果您确实想要一个列表,您可以使用以下命令将迭代器转换为列表:
instances = list(ec2.instances.filter())
Run Code Online (Sandbox Code Playgroud)