如何解决以下错误
[system@root selectami]$ python latest-ami.py eu-west-1
Traceback (most recent call last):
File "latest-ami.py", line 60, in <module>
print(source_image['ImageId'])
TypeError: 'NoneType' object has no attribute '__getitem__'
[system@root selectami]$
#!/usr/bin/env python
import boto3
import sys
from dateutil import parser
region = sys.argv[1]
def newest_image(list_of_images):
latest = None
for image in list_of_images:
if not latest:
latest = image
continue
if parser.parse(image['CreationDate']) > parser.parse(latest['CreationDate']):
latest = image
return latest
client = boto3.client('ec2', region_name=region)
filters = [ {
'Name': 'name',
'Values': ['amzn-ami-hvm-*']
},{
'Name': 'description',
'Values': ['Amazon Linux AMI*']
},{
'Name': 'architecture',
'Values': ['x86_64']
},{
'Name': 'owner-alias',
'Values': ['amazon']
},{
'Name': 'owner-id',
'Values': ['137112412989']
},{
'Name': 'state',
'Values': ['available']
},{
'Name': 'root-device-type',
'Values': ['ebs']
},{
'Name': 'virtualization-type',
'Values': ['hvm']
},{
'Name': 'hypervisor',
'Values': ['xen']
},{
'Name': 'image-type',
'Values': ['machine']
} ]
response = client.describe_images(Owners=['amazon'], Filters=filters)
source_image = newest_image(response['Images'])
print(source_image['ImageId'])
答案 0 :(得分:1)
您的newest_image
似乎返回None
,因此,您的print
调用了None['ImageId']
,这就是您得到错误的地方。检查response['Images']
是否为空列表,如果是,请适当地更改过滤器,以获取一些有效的返回值
答案 1 :(得分:0)
source_image
是None
,因此newest_image(response['Images'])
是None
,因此list_of_images
没有image
就是False
并且没有{ {1}},以使image
为真。
您可以更改parser.parse(image['CreationDate']) > parser.parse(latest['CreationDate'])
以在找不到新图像时引发错误,而不是返回newest_image
。
答案 2 :(得分:0)
在此处的功能中-
def newest_image(list_of_images): # list_of_images is passed here, which in your case is []
latest = None # latest is set to None here
# Since list_of_images is empty, this for loop does not work
for image in list_of_images:
if not latest:
latest = image
continue
if parser.parse(image['CreationDate']) > parser.parse(latest['CreationDate']):
latest = image
# since for loop did not run, latest still is None
return latest
出现此错误的原因是因为newest_image
返回了None
,因此source_image
为None,并且--p
print(source_image['ImageId'])
您正在尝试从None
中获取项目,因此-
TypeError: 'NoneType' object has no attribute '__getitem__'
您可以像处理-
try:
print(source_image['ImageId'])
except TypeError:
print("Oops! Returned None")
我希望这有意义吗?