python - 在 Python 中处理超时异常

标签 python exception timeout handle praw

我正在寻找一种方法来处理使用 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/

相关文章:

java - 控制 - Java 中的 C 异常

cocoa - 可以使用 Xcode 或解释获取异常位置...我怎样才能同时获得两者?

java - 向 Servlet 中抛出异常

bash - 在没有不必要延迟的情况下使 bash 中的命令超时

spring - JTA/JTS 如何处理事务超时问题?

Python xlsx单元格保护(锁)

python - pytest Flask-SQLAlchemy session 中的完整性错误

python - 如何增加 imaplib 请求的超时时间?

python - 跨列添加 Pandas 字符串

javascript - 使用箭头键和智能延迟加载实现有机列表浏览