在 Python 中处理超时异常

Mat*_* T. 5 python timeout exception 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
Run Code Online (Sandbox Code Playgroud)

Alu*_*Alu 2

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

你可以让 apass不执行任何操作并继续循环。

try:
    run_bot()
except:
    pass
Run Code Online (Sandbox Code Playgroud)

在你的情况下,最好将其明确写为

try:
    run_bot()
except:
    continue
Run Code Online (Sandbox Code Playgroud)

但您也可以向 except 子句添加一些日志记录

try:
    run_bot()
except e:
    print 'Loading failed due to Timeout'
    print e
Run Code Online (Sandbox Code Playgroud)

为了确保循环始终处于休眠状态,您可以执行以下操作:

nr_of_comments = 0

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

while True:
    sleep(10)
    try:
        run_bot()
    except e:
        continue
Run Code Online (Sandbox Code Playgroud)