python中所有ec2实例的csv输出
我正在尝试在csv文件中获取所有ec2实例的详细信息,随后发布了另一篇帖子“https://stackoverflow.com/questions/62815990/export-aws-ec2-details-to-xlsx-csv-using-boto3-and-python". 但实例的属性错误。所以我试着这样做:python中所有ec2实例的csv输出,python,amazon-web-services,amazon-ec2,Python,Amazon Web Services,Amazon Ec2,我正在尝试在csv文件中获取所有ec2实例的详细信息,随后发布了另一篇帖子“https://stackoverflow.com/questions/62815990/export-aws-ec2-details-to-xlsx-csv-using-boto3-and-python". 但实例的属性错误。所以我试着这样做: import boto3 import datetime import csv ec2 = boto3.resource('ec2')
import boto3
import datetime
import csv
ec2 = boto3.resource('ec2')
for i in ec2.instances.all():
Id = i.id
State = i.state['Name']
Launched = i.launch_time
InstanceType = i.instance_type
Platform = i.platform
if i.tags:
for idx, tag in enumerate(i.tags, start=1):
if tag['Key'] == 'Name':
Instancename = tag['Value']
output = Instancename + ',' + Id + ',' + State + ',' + str(Platform) + ',' + InstanceType + ',' + str(Launched)
with open('ec2_list.csv', 'w', newline='') as csvfile:
header = ['Instancename', 'Id', 'State', 'Platform', 'InstanceType', 'Launched']
writer = csv.DictWriter(csvfile, fieldnames=header)
writer.writeheader()
writer.writerow(output)
对于以上内容,我有以下错误:
traceback (most recent call last):
File "list_instances_2.py", line 23, in <module>
writer.writerow(output)
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/csv.py", line 155, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/csv.py", line 148, in _dict_to_list
wrong_fields = rowdict.keys() - self.fieldnames
AttributeError: 'str' object has no attribute 'keys'
回溯(最近一次呼叫最后一次):
文件“list_instances_2.py”,第23行,在
writer.writerow(输出)
文件“/usr/local/ceral/python/3.7.5/Frameworks/python.framework/Versions/3.7/lib/python3.7/csv.py”,第155行,writerow格式
返回self.writer.writerow(self.\u dict\u to\u list(rowdict))
文件“/usr/local/ceral/python/3.7.5/Frameworks/python.framework/Versions/3.7/lib/python3.7/csv.py”,第148行,在目录列表中
错误的_fields=rowdict.keys()-self.fieldnames
AttributeError:“str”对象没有属性“keys”
我可以看出,这并不是创建dict输出。需要关于如何创建“输出”词典并将其发布到.csv文件中的建议。a——顾名思义——将词典写入csv文件。字典必须具有与列名对应的键。请参见我链接的文档中的示例
在您发布的代码中,您正在向writerow
函数传递output
——一个字符串。这将不起作用,因为字符串不是dict
您必须将输出
转换为writerow
可以接受的内容,例如命令
:
output = {'Instancename': Instancename, 'Id': Id ... }
然后再试一次。由于您使用的是
DictWriter
,您的输出应该是:
output = {
'Instancename': Instancename,
'Id': Id,
'State': State,
'Platform': str(Platform),
'InstanceType': InstanceType ,
'Launched': str(Launched)
}
在每次迭代中,您的函数也将继续覆盖您的ec2_list.csv
,因此您可能应该重新考虑它