简体   繁体   中英

Test Multiple Conditions in Python Try statement

I'm getting a list of aws ec2 instances with these command:

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

I need to see if each instance has a Private IP and a Public IP. If I use a try statement for both I get a syntax error:

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

This is the error:

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

If I use an if statement instead of a try, python complains that the key doesn't exist if the machine doesn't have a public ip:

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

I get this error:

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

What's the right way to go about this?

You should check if the key is in the dictionary:

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

Note, that this will just test whether those keys are present in the dictionary, but not if they have a meaningful value, eg depending on how you get your data they might be None or empty strings "" . Alterantively, you could also use get to get the values, or None if they are not present.

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

Here, the values are implicitly interpreted as bool , ie both None (or not-present) and empty string values would be considered False .

Try statements are used for capturing various exceptions, such as the KeyError . You'd use them as such:

try:
    if instance['PrivateIpAddress'] and instance['PublicIpAddress']:
        # do something
except KeyError:
        # do something else

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM