python - Python None 值未应用
问题描述
我正在尝试在 AWS 实例中查找键和值。如果键存在,我希望脚本在存在时报告值,或者None
在键没有值时报告。
我为许多键值对执行此操作,除了一个之外,它们都可以工作。
None
如果键没有值,这些键/值对会报告:
instance_list = ec2.describe_instances()
for reservation in instance_list["Reservations"]:
for instance in reservation.get("Instances", []):
if instance['PublicDnsName']:
public_dns_name = instance['PublicDnsName']
else:
public_dns_name = None
if 'KeyName' in instance:
key_name = instance['KeyName']
else:
key_name = None
这个总是显示一个空白值而不是None
. 当它们的键有值时,它会报告一个值:
if 'PrivateDnsName' in instance:
private_dns = instance['PrivateDnsName']
else:
private_dns = None
以下是instance
实例 ID 的值,其中显示 的空白条目private_dns
:
{'AmiLaunchIndex': 0, 'ImageId': 'ami-062f7200baf2fa504', 'InstanceId': 'i-02fa5c552a10ddfca', 'InstanceType': 't2.micro', 'KeyName': 'sncr-timd', 'LaunchTime': datetime.datetime(2020, 1, 14, 22, 25, tzinfo=tzutc()), 'Monitoring': {'State': 'disabled'}, 'Placement': {'AvailabilityZone': 'us-east-1b', 'GroupName': '', 'Tenancy': 'default'}, 'PrivateDnsName': '', 'ProductCodes': [], 'PublicDnsName': '', 'State': {'Code': 48, 'Name': 'terminated'}, 'StateTransitionReason': 'User initiated (2020-01-15 14:43:16 GMT)', 'Architecture': 'x86_64', 'BlockDeviceMappings': [], 'ClientToken': '', 'EbsOptimized': False, 'EnaSupport': True, 'Hypervisor': 'xen', 'NetworkInterfaces': [], 'RootDeviceName': '/dev/xvda', 'RootDeviceType': 'ebs', 'SecurityGroups': [], 'StateReason': {'Code': 'Client.UserInitiatedShutdown', 'Message': 'Client.UserInitiatedShutdown: User initiated shutdown'}, 'VirtualizationType': 'hvm', 'CpuOptions': {'CoreCount': 1, 'ThreadsPerCore': 1}, 'CapacityReservationSpecification': {'CapacityReservationPreference': 'open'}, 'HibernationOptions': {'Configured': False}, 'MetadataOptions': {'State': 'pending', 'HttpTokens': 'optional', 'HttpPutResponseHopLimit': 1, 'HttpEndpoint': 'enabled'}}
这是当instance
确实有private_dns
键和值时输出的样子:
Private DNS: ip-172-31-37-19.us-east-2.compute.internal
这是存在instance
时的外观private_dns
:
{'AmiLaunchIndex': 0, 'ImageId': 'ami-02ccb28830b645a41', 'InstanceId': 'i-069e87e16db1bf49b', 'InstanceType': 't2.micro', 'KeyName': 'sncr-timd', 'LaunchTime': datetime.datetime(2020, 1, 14, 22, 27, 17, tzinfo=tzutc()), 'Monitoring': {'State': 'disabled'}, 'Placement': {'AvailabilityZone': 'us-east-2c', 'GroupName': '', 'Tenancy': 'default'}, 'PrivateDnsName': 'ip-172-31-37-19.us-east-2.compute.internal', 'PrivateIpAddress': '172.31.37.19', 'ProductCodes': [], 'PublicDnsName': 'ec2-18-223-15-106.us-east-2.compute.amazonaws.com', 'PublicIpAddress': '18.223.15.106', 'State': {'Code': 16, 'Name': 'running'}, 'StateTransitionReason': '', 'SubnetId': 'subnet-22038f6e', 'VpcId': 'vpc-859c5aee', 'Architecture': 'x86_64', 'BlockDeviceMappings': [{'DeviceName': '/dev/xvda', 'Ebs': {'AttachTime': datetime.datetime(2020, 1, 14, 22, 27, 18, tzinfo=tzutc()), 'DeleteOnTermination': True, 'Status': 'attached', 'VolumeId': 'vol-08f30292b9a7039bc'}}], 'ClientToken': '', 'EbsOptimized': False, 'EnaSupport': True, 'Hypervisor': 'xen', 'NetworkInterfaces': [{'Association': {'IpOwnerId': 'amazon', 'PublicDnsName': 'ec2-18-223-15-106.us-east-2.compute.amazonaws.com', 'PublicIp': '18.223.15.106'}, 'Attachment': {'AttachTime': datetime.datetime(2020, 1, 14, 22, 27, 17, tzinfo=tzutc()), 'AttachmentId': 'eni-attach-0937973380674deef', 'DeleteOnTermination': True, 'DeviceIndex': 0, 'Status': 'attached'}, 'Description': '', 'Groups': [{'GroupName': 'launch-wizard-1', 'GroupId': 'sg-08b8c8a89bcc3c692'}], 'Ipv6Addresses': [], 'MacAddress': '0a:d9:9b:03:a7:a8', 'NetworkInterfaceId': 'eni-0bfcd12253ecf87ec', 'OwnerId': '565241749827', 'PrivateDnsName': 'ip-172-31-37-19.us-east-2.compute.internal', 'PrivateIpAddress': '172.31.37.19', 'PrivateIpAddresses': [{'Association': {'IpOwnerId': 'amazon', 'PublicDnsName': 'ec2-18-223-15-106.us-east-2.compute.amazonaws.com', 'PublicIp': '18.223.15.106'}, 'Primary': True, 'PrivateDnsName': 'ip-172-31-37-19.us-east-2.compute.internal', 'PrivateIpAddress': '172.31.37.19'}], 'SourceDestCheck': True, 'Status': 'in-use', 'SubnetId': 'subnet-22038f6e', 'VpcId': 'vpc-859c5aee', 'InterfaceType': 'interface'}], 'RootDeviceName': '/dev/xvda', 'RootDeviceType': 'ebs', 'SecurityGroups': [{'GroupName': 'launch-wizard-1', 'GroupId': 'sg-08b8c8a89bcc3c692'}], 'SourceDestCheck': True, 'VirtualizationType': 'hvm', 'CpuOptions': {'CoreCount': 1, 'ThreadsPerCore': 1}, 'CapacityReservationSpecification': {'CapacityReservationPreference': 'open'}, 'HibernationOptions': {'Configured': False}, 'MetadataOptions': {'State': 'applied', 'HttpTokens': 'optional', 'HttpPutResponseHopLimit': 1, 'HttpEndpoint': 'enabled'}}
我想知道为什么会这样。我该如何纠正?
解决方案
我认为关键PrivateDnsName
总是轴,尝试改变:
private_dns = instance['PrivateDnsName']
和
private_dns = instance['PrivateDnsName'] if instance['PrivateDnsName'] else None
编辑
为避免可能KeyError
,您可以使用.get()
vpc_id = instance.get('VpcId') if instance.get('VpcId') else None
推荐阅读
- push-notification - 当应用程序被杀死时,推送通知不显示消息正文。它只显示应用程序的默认图标
- android - 带有 configChanges 的 Android DayNight 主题
- go - 用结构方法反射结构
- python - Python - Selenium 不会返回上一页
- mysql - 从 MySQL 数据库中选择多个字段重复项
- jquery - 从不同页面导航到主选项卡内的子选项卡
- android - 如何使用 Android Renderscript 填充位图?
- javascript - if { ... } 外部的 Javascript XMLHttpRequest 状态
- angular - 弹性网格不适用于 p-col-#primeng Angular 5
- git - 初始推送后 Git 忽略文件(只读)