Python 类型错误:';非类型';对象没有属性'__获取项目';最新版本-ami.py

Python 类型错误:';非类型';对象没有属性'__获取项目';最新版本-ami.py,python,Python,如何修复以下错误 [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__' [sys

如何修复以下错误

[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]$

您的
最新图片
似乎返回
None
,因此,您的
print
调用
None['ImageId']
,这就是出现错误的原因。检查
响应['Images']
是否为空列表,如果是空列表,请适当更改过滤器,以便获得一些有效的返回值
源图像
,因此
最新图像(响应['Images'])
因此
图像列表
没有
图像
为假
且没有
图像
,因此
解析器.parse(image['CreationDate']>parser.parse(latest['CreationDate'])
为真

您可以更改
最新\u图像
,以在未找到新图像时引发错误,而不是在此处的函数中返回

-

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
出现此错误的原因是
最新的\u图像
返回
,因此
源图像
为无-

print(source_image['ImageId'])
因此,您正试图从
None
获取一个项目-

TypeError: 'NoneType' object has no attribute '__getitem__'
你可以像这样处理它-

try:
    print(source_image['ImageId'])
except TypeError:
    print("Oops! Returned None")

我希望这是有意义的?

修复缩进您能
打印(源图像)
吗?如果
响应
为空,则
响应[“图像”]
将引发
键错误
。显然是
response[“Images”]
是空的。你让我想,response一定是
None
这就是为什么error说
NoneType
,如果它是空的,它应该是
KeyError
@brunodesthuilliers请更仔细地重新阅读回溯-错误发生在这里:
print(source\u image['ImageId'))
-尝试访问
响应[“图像”]
时没有。谢谢大家,我的印象是“响应[“图像”]”将从筛选条件中获得一个值。。正确的语法是什么?你能打印
响应
@m.jack吗?
try:
    print(source_image['ImageId'])
except TypeError:
    print("Oops! Returned None")