我有以下python boto3代码,可能有无限while-loop
。通常,几分钟后while-loop
成功。但是,如果AWS端出现问题,程序可能会无限期挂起。
我确信这不是最合适的方法。
# credentials stored in ../.aws/credentials
# region stored in ../.aws/config
# builtins
from time import sleep
# plugins
import boto3
# Assign server instance IDs.
cye_production_web_server_2 = 'i-FAKE-ID'
# Setup EC2 client
ec2 = boto3.client('ec2')
# Start the second web server.
start_response = ec2.start_instances(
InstanceIds=[cye_production_web_server_2, ],
DryRun=False
)
print(
'instance id:',
start_response['StartingInstances'][0]['InstanceId'],
'is',
start_response['StartingInstances'][0]['CurrentState']['Name']
)
# Wait until status is 'ok'
status = None
while status != 'ok':
status_response = ec2.describe_instance_status(
DryRun=False,
InstanceIds=[cye_production_web_server_2, ],
)
status = status_response['InstanceStatuses'][0]['SystemStatus']['Status']
sleep(5) # 5 second throttle
print(status_response)
print('status is', status.capitalize())
答案 0 :(得分:3)
在循环中实现计数器并在经过多次尝试后失败
status = None
counter = 5
while (status != 'ok' and counter > 0):
status_response = ec2.describe_instance_status(
DryRun=False,
InstanceIds=[cye_production_web_server_2, ],
)
status = status_response['InstanceStatuses'][0]['SystemStatus']['Status']
sleep(5) # 5 second throttle
counter=counter-1
print(status_response)
print('status is', status.capitalize())
答案 1 :(得分:0)
你可以尝试在map
循环中进行,而不是尝试固定次数。
例如:
for
答案 2 :(得分:0)
使用超时可能是一个更好的主意
import time
systemstatus = False
timeout = time.time() + 60*minute
while systemstatus is not True:
status = ec2.describe_instance_status( \
DryRun = False,
InstanceIds = [instance_id]
)
if status['InstanceStatuses'][0]['SystemStatus']['Status'] == 'ok':
systemstatus = True
if time.time() > timeout:
break
else:
time.sleep(10)