python-3.x - 异常后继续 - Python
问题描述
我试图在我的代码中阻止try
并except
阻止错误,然后让它休眠 5 秒钟,然后我想从它停止的地方继续。以下是我的代码,目前一旦它捕获异常,它就不会继续并在异常后停止。
from botocore.exceptions import ClientError
tries = 0
try:
for pag_num, page in enumerate(one_submitted_jobs):
if 'NextToken' in page:
print("Token:",pag_num)
else:
print("No Token in page:", pag_num)
except ClientError as exception_obj:
if exception_obj.response['Error']['Code'] == 'ThrottlingException':
print("Throttling Exception Occured.")
print("Retrying.....")
print("Attempt No.: " + str(tries))
time.sleep(5)
tries +=1
else:
raise
异常后如何使其继续?任何帮助都会很棒。
注意 - 我试图ThrottlingException
在我的代码中捕捉 AWS 的错误。
以下代码用于向@Selcuk 演示,以显示我目前从他的回答中得到的信息。一旦我们同意我的操作是否正确,以下内容将被删除。
tries = 1
pag_num = 0
# Only needed if one_submitted_jobs is not an iterator:
one_submitted_jobs = iter(one_submitted_jobs)
while True:
try:
page = next(one_submitted_jobs)
# do things
if 'NextToken' in page:
print("Token: ", pag_num)
else:
print("No Token in page:", pag_num)
pag_num += 1
except StopIteration:
break
except ClientError as exception_obj:
# Sleep if we are being throttled
if exception_obj.response['Error']['Code'] == 'ThrottlingException':
print("Throttling Exception Occured.")
print("Retrying.....")
print("Attempt No.: " + str(tries))
time.sleep(3)
tries +=1
解决方案
您无法继续运行,因为您的for
线路发生异常。这有点棘手,因为在这种情况下,for
语句无法知道是否还有更多项目要处理。
一种解决方法可能是使用while
循环:
pag_num = 0
# Only needed if one_submitted_jobs is not an iterator:
one_submitted_jobs = iter(one_submitted_jobs)
while True:
try:
page = next(one_submitted_jobs)
# do things
pag_num += 1
except StopIteration:
break
except ClientError as exception_obj:
# Sleep if we are being throttled
推荐阅读
- azure-devops - 如何为 sprint 创建 Azure DevOps wiki 报告?
- sql - 横向嵌套-SQL
- javascript - 在新选项卡/窗口中传递数据或修改扩展 html
- c++ - 删除移动到容器的对象时的 SIGABRT
- algorithm - AVL 树 - 为什么在插入后回溯
- google-apps-script - 使用存储在 GoogleSheets 中的文件名获取 GooglePhoto 的脚本
- react-native - 是否可以使用本机反应加密 android 设备的图像?
- opennms - centeron 18 不能与远程轮询器和远程服务器一起使用。为什么?
- python - Spark 中的多输出分类
- ssas-tabular - 如何更新源表中的表格数据