超时或错误后重新运行 python 脚本
Rerunning python script after a timeout or an error
我正在尝试找到一种方法,如果出现超时或错误,我可以重新 运行 我的代码。
如果互联网连接断开,就会发生这种情况 - 所以我需要延迟几秒钟,等它恢复在线后再试一次..
有没有办法让我在另一个 python 脚本中 运行 我的代码,并在它超时或断开连接时告诉它重新 运行?
提前致谢
你实际上可以用 try except
块来做到这一点。
您可以在这里找到所有相关信息:https://docs.python.org/3/tutorial/errors.html
你只需制作一个脚本,其中包含类似的内容:
while True:
try:
another_script_name.main()
except:
time.sleep(20)
当然,您需要同时导入时间和您制作的其他脚本。
这些行所做的只是一个无限循环,它总是尝试 运行 您编写的其他脚本的主要功能,如果发生某种错误,系统将休眠 20 秒,然后重试,因为它在无限循环中。
您可以像这样在无限循环中使用 try-catch:
while True:
try:
# your code
# call another python script
except:
time.sleep(10)
此外,您可以检查错误和 运行 任何您需要 运行 的内容,具体取决于错误类型。例如:
while True:
try:
# your code
# call another python script
# break
except Exception as e:
if e == 'error type':
time.sleep(10)
else:
pass
如果您正在谈论 http 请求连接错误,并且如果您正在使用请求库,则可以使用此 urllib retry
仅供参考 https://docs.python-requests.org/en/master/api/#requests.adapters.HTTPAdapter
当然其他库也会有自己的重试功能。
如果您只想要简单的重试代码,请使用以下代码
retries_count = 3 # hard value
delay = 3 # hard value
while True:
try:
... run some code
return or break
except {Your Custom Error}:
if retries_count <= 0:
raise
retries_count -= 1
time.sleep(delay)
一个Google搜索“python throttling”会给你很多参考。
我正在尝试找到一种方法,如果出现超时或错误,我可以重新 运行 我的代码。
如果互联网连接断开,就会发生这种情况 - 所以我需要延迟几秒钟,等它恢复在线后再试一次..
有没有办法让我在另一个 python 脚本中 运行 我的代码,并在它超时或断开连接时告诉它重新 运行?
提前致谢
你实际上可以用 try except
块来做到这一点。
您可以在这里找到所有相关信息:https://docs.python.org/3/tutorial/errors.html
你只需制作一个脚本,其中包含类似的内容:
while True:
try:
another_script_name.main()
except:
time.sleep(20)
当然,您需要同时导入时间和您制作的其他脚本。 这些行所做的只是一个无限循环,它总是尝试 运行 您编写的其他脚本的主要功能,如果发生某种错误,系统将休眠 20 秒,然后重试,因为它在无限循环中。
您可以像这样在无限循环中使用 try-catch:
while True:
try:
# your code
# call another python script
except:
time.sleep(10)
此外,您可以检查错误和 运行 任何您需要 运行 的内容,具体取决于错误类型。例如:
while True:
try:
# your code
# call another python script
# break
except Exception as e:
if e == 'error type':
time.sleep(10)
else:
pass
如果您正在谈论 http 请求连接错误,并且如果您正在使用请求库,则可以使用此 urllib retry
仅供参考 https://docs.python-requests.org/en/master/api/#requests.adapters.HTTPAdapter
当然其他库也会有自己的重试功能。
如果您只想要简单的重试代码,请使用以下代码
retries_count = 3 # hard value
delay = 3 # hard value
while True:
try:
... run some code
return or break
except {Your Custom Error}:
if retries_count <= 0:
raise
retries_count -= 1
time.sleep(delay)
一个Google搜索“python throttling”会给你很多参考。