TypeError:“ NoneType”对象没有属性“ __getitem __” latest-ami.py

时间:2018-07-24 11:07:43

标签: 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__'
[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'])

3 个答案:

答案 0 :(得分:1)

您的newest_image似乎返回None,因此,您的print调用了None['ImageId'],这就是您得到错误的地方。检查response['Images']是否为空列表,如果是,请适当地更改过滤器,以获取一些有效的返回值

答案 1 :(得分:0)

source_imageNone,因此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")

我希望这有意义吗?