如何修复以下错误
[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'])
您的newest_image
似乎返回None
,因此,您的print
调用None['ImageId']
,这就是您得到错误的地方。检查response['Images']
是否不是一个空列表,如果是,则适当地更改过滤器,以便获得一些有效的返回值
source_image
是None
,因此newest_image(response['Images'])
是None
,因此list_of_images
没有image
是False
,也没有image
,从而parser.parse(image['CreationDate']) > parser.parse(latest['CreationDate'])
为真。
您可以更改newest_image
以在未找到新映像时引发错误,而不是返回None
。
在这里的函数中-
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,此时-
print(source_image['ImageId'])
您正试图从None
中获取一个项目,因此-
TypeError: 'NoneType' object has no attribute '__getitem__'
你可以像一样处理它
try:
print(source_image['ImageId'])
except TypeError:
print("Oops! Returned None")
我希望这有道理?