【问题标题】:Handling a timeout exception in Python在 Python 中处理超时异常
【发布时间】:2017-01-24 18:33:40
【问题描述】:

我正在寻找一种方法来处理我的 Reddit 机器人使用 PRAW (Python) 的超时异常。它每天至少超时一次,并且它有一个编码的变量,所以我必须更新变量,然后再次手动运行机器人。我正在寻找一种自动处理这些异常的方法。我研究了 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

【问题讨论】:

    标签: python exception timeout handle praw


    【解决方案1】:

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

    您可以创建一个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
    

    【讨论】:

    • 我应该补充一点,bot的功能之一是,当它有一段时间没有检测到评论时,它会休眠10秒,然后再次检查,这样它就不会保持垃圾邮件 Reddit。如果我要执行 except: continue,循环是否仍会像 try:run_bot() 一样运行?有什么办法可以让你睡在那里?
    • 我试图理解:如果没有发现任何新内容,run_bot 本身会休眠 10 秒。在run_bot 完成后你又睡了吗?那么究竟什么时候抛出异常呢?
    • 我相信当它尝试连接到 Reddit 但失败时会引发异常。 run_bot(10) 之后的睡眠是唯一的睡眠
    • 然后我会在 run_bot 之前放置睡眠并继续在除此之外。所以循环将休眠 10 秒并运行机器人。如果发生错误,则循环再次开始...您也可以将 sleep 放在 try-except 之外,以确保循环将始终休眠 10s
    • 抱歉所有问题,但这样做会使程序重置变量吗?例如,我声明变量 = 10,每次看到评论时,它都会给变量加 1。那么如果最终变量 = 14,并且它捕获了异常,那么变量仍然是 14 吗?
    【解决方案2】:

    我猜,将睡眠移至 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-19
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 2015-02-03
      • 1970-01-01
      相关资源
      最近更新 更多