在Python Try语句中测试多个条件

问题描述 投票:0回答:2

我正在使用这些命令获取aws ec2实例的列表:

response = ec2.describe_instances()
for reservation in response["Reservations"]:
    for instance in reservation["Instances"]:

我需要查看每个实例是否都有私有IP和公共IP。如果我对两者都使用try语句,则会出现语法错误:

try instance['PrivateIpAddress']  and instance['PublicIpAddress']:

这是错误:

File ".\aws_ec2_list_instances.py", line 26
    try instance['PrivateIpAddress']  and instance['PublicIpAddress']:
               ^
SyntaxError: invalid syntax

如果我使用if语句而不是try,python会抱怨如果机器没有公共ip,则密钥不存在:

if instance['PrivateIpAddress'] and instance['PublicIpAddress']:

我收到此错误:

Traceback (most recent call last):
  File ".\aws_ec2_list_instances.py", line 26, in <module>
    if instance['PrivateIpAddress'] and instance['PublicIpAddress']:
KeyError: 'PublicIpAddress'

什么是正确的方法?

python boto
2个回答
2
投票

你应该检查if关键是in字典:

if 'PrivateIpAddress' in instance and 'PublicIpAddress' in instance:

注意,这只是测试字典中是否存在这些键,但是如果它们具有有意义的值,则不会,例如,根据你获得数据的方式,他们可能是None或空字符串""。另外,您也可以使用get来获取值,如果不存在则使用None

if instance.get('PrivateIpAddress') and instance.get('PublicIpAddress'):

这里,值被隐含地解释为bool,即None(或不存在)和空字符串值都被认为是False


1
投票

Try语句用于捕获各种异常,例如KeyError。你可以这样使用它们:

try:
    if instance['PrivateIpAddress'] and instance['PublicIpAddress']:
        # do something
except KeyError:
        # do something else
© www.soinside.com 2019 - 2024. All rights reserved.