在 Python Try 语句中测试多个条件
Test Multiple Conditions in Python Try statement
我正在使用这些命令获取 aws ec2 实例列表:
response = ec2.describe_instances()
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
我需要查看是否每个实例都有一个私有 IP 和一个 Public 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,如果机器没有 public ip:
,python 会抱怨密钥不存在
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'
解决这个问题的正确方法是什么?
Try
语句用于捕获各种异常,例如KeyError
。您可以这样使用它们:
try:
if instance['PrivateIpAddress'] and instance['PublicIpAddress']:
# do something
except KeyError:
# do something else
你应该检查 if
关键是 in
字典:
if 'PrivateIpAddress' in instance and 'PublicIpAddress' in instance:
请注意,这只会测试字典中是否存在这些键,但不会测试它们是否具有有意义的值,例如根据您获取数据的方式,它们可能是 None
或空字符串 ""
。或者,您也可以使用 get
来获取值,或者如果它们不存在则使用 None
。
if instance.get('PrivateIpAddress') and instance.get('PublicIpAddress'):
此处,值被隐式解释为 bool
,即 None
(或不存在)和空字符串值都将被视为 False
。
我正在使用这些命令获取 aws ec2 实例列表:
response = ec2.describe_instances()
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
我需要查看是否每个实例都有一个私有 IP 和一个 Public 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,如果机器没有 public ip:
,python 会抱怨密钥不存在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'
解决这个问题的正确方法是什么?
Try
语句用于捕获各种异常,例如KeyError
。您可以这样使用它们:
try:
if instance['PrivateIpAddress'] and instance['PublicIpAddress']:
# do something
except KeyError:
# do something else
你应该检查 if
关键是 in
字典:
if 'PrivateIpAddress' in instance and 'PublicIpAddress' in instance:
请注意,这只会测试字典中是否存在这些键,但不会测试它们是否具有有意义的值,例如根据您获取数据的方式,它们可能是 None
或空字符串 ""
。或者,您也可以使用 get
来获取值,或者如果它们不存在则使用 None
。
if instance.get('PrivateIpAddress') and instance.get('PublicIpAddress'):
此处,值被隐式解释为 bool
,即 None
(或不存在)和空字符串值都将被视为 False
。