[英]Sleep in case of error, python
所以我有一种情况,我将连续12小时使用互联网连接并打电话给api。 但每隔10分钟,Light就会继续消失。 可以写一个try,除了在产生超时错误的情况下会导致10分钟延迟的函数。 电力将在10分钟内恢复,这是有希望的 这就是我目前使用的:
try:
a=translator.translate(str(x1),dest='hi')
b=translator.translate(str(x2),dest='hi')
except:
sleep(60*10)
您可以使用retry
模块在异常上进行这些重试。 这使代码看起来更清晰。 pip install retry
应该安装模块
from retry import retry
@retry(Exception, delay=10*60, tries=-1)
def my_code_that_needs_to_be_retried_for_ever():
a=translator.translate(str(x1),dest='hi')
b=translator.translate(str(x2),dest='hi')
# Call the function
my_code_that_needs_to_be_retried_for_ever()
使用上面的代码,当调用my_code_that_needs_to_be_retried_for_ever
时,每次执行块内的代码引发异常时,它将每60 * 10秒(10分钟)永久重试(因为my_code_that_needs_to_be_retried_for_ever
设置为-1)
使用try
和except
捕获异常,然后使用time.sleep
使Python脚本在所需的时间内休眠。 然后你可以把里面的东西无限while
循环和break
的它曾经的一切结束了。
while True:
try:
# put everything here which might produce exception
pass
# if this point is reached everything worked fine, so exit loop
break
except:
time.sleep(10*60)
您可以运行以下示例来查看一般概念:
import random
import time
print("Before loop")
while True:
try:
print("Try to execute commands")
# your commands here
if random.random() > 0.3:
print("Randomly simulate timeout")
raise Exception("Timeout")
print("Everything done")
break
except:
print("Timeout: sleep for 2 seconds and try again")
time.sleep(2)
print("After loop")
我们随机决定引发异常以模拟超时,而不是真正的命令。 结果可能如下所示:
Before loop Try to execute commands Randomly simulate timeout Timeout: sleep for 2 seconds and try again Try to execute commands Randomly simulate timeout Timeout: sleep for 2 seconds and try again Try to execute commands Randomly simulate timeout Timeout: sleep for 2 seconds and try again Try to execute commands Everything done After loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.