在 Python 中处理超时异常

Handling a timeout exception in Python

我正在寻找一种方法来处理使用 PRAW (Python) 的 Reddit 机器人的超时异常。它每天至少超时一次,并且它有一个编码的变量,所以我必须更新变量,然后再次手动 运行 机器人。我正在寻找一种自动处理这些异常的方法。我研究了 try: 和 except:,但我担心在 time.sleep(10) 之后添加一个断点会完全停止循环。我希望它保持 运行ning 循环,不管它是否超时。下面是代码示例。

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

这取决于发生超时时你想做什么。

你可以让 pass 什么也不做,然后继续循环。

try:
    run_bot()
except:
    pass

在你的情况下,最好明确地写成

try:
    run_bot()
except:
    continue

但是你也可以在 except 子句中添加一些日志记录

try:
    run_bot()
except e:
    print 'Loading failed due to Timeout'
    print e

要确保循环始终休眠,您可以执行以下操作:

nr_of_comments = 0

def run_bot():
    # do stuff
    nr_of_comments =+ 1

while True:
    sleep(10)
    try:
        run_bot()
    except e:
        continue

我想将睡眠移至 finally 将解决您的问题。 finally 块将 运行 不管是否有异常发生。

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)