我正在寻找一种方法来处理使用 PRAW (Python) 的 Reddit 机器人的超时异常。它每天至少超时一次,并且它有一个编码的变量,所以我必须更新变量,然后再次手动运行机器人。我正在寻找一种自动处理这些异常的方法。我研究了 try: 和 except:,但我担心在 time.sleep(10) 之后添加一个断点会完全停止循环。我希望它继续运行循环,无论它是否超时。下面是代码示例。
def run_bot():
# Arbitrary Bot Code Here
# This is at the bottom of the code, and it runs the above arbitrary code every 10 seconds
while True:
try:
run_bot()
time.sleep(10)
except:
# Don't know what goes here
最佳答案
我想将 sleep 移至 finally 将解决您的问题。无论是否发生异常,finally block 都会运行。
def run_bot():
# Arbitrary Bot Code Here
# This is at the bottom of the code, and it runs the above arbitrary code every 10 seconds
while True:
try:
run_bot()
except:
from traceback import format_exc
print "Exception happened:\n%s" % (format_exc())
finally:
time.sleep(10)
关于python - 在 Python 中处理超时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39533022/