因此,我遇到这样的情况,我要连续12个小时使用互联网连接并拨打api。但是光每隔10分钟就会熄灭一次。可以编写一个try,但函数会导致10分钟的延迟,以防产生超时错误。希望能在10分钟内恢复供电。 这是我目前正在使用的:
try:
a=translator.translate(str(x1),dest='hi')
b=translator.translate(str(x2),dest='hi')
except:
sleep(60*10)
答案 0 :(得分: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
答案 1 :(得分:1)
您可以使用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
时,只要功能块中的代码引发Exception,每60 * 10秒(10分钟)将重试一次(尝试次数设置为-1)。 / p>