Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling a timeout exception in Python

I'm looking for a way to handle timeout exceptions for my Reddit bot which uses PRAW (Python). It times out at least once every day, and it has a variable coded in so I have to update the variable and then manually run the bot again. I am looking for a way to automatically handle these exceptions. I looked into try: and except:, but I am afraid that adding a break point after time.sleep(10) would stop the loop completely. I want it to keep running the loop regardless if it times out or not. There is a sample of the code below.

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
like image 329
Matt T. Avatar asked Sep 16 '16 13:09

Matt T.


2 Answers

Moving the sleep to finally will solve your issue, I guess. finally block will run irrespective of whether there is an exception happened or not.

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)
like image 197
thiruvenkadam Avatar answered Sep 20 '22 23:09

thiruvenkadam


It depends on what you want to do when a timeout occurs.

you can make a pass to do nothing and continue with the loop.

try:
    run_bot()
except:
    pass

In your case it would be better to write it explicitly as

try:
    run_bot()
except:
    continue

But you can also add some logging to the except clause

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

To make sure the loop always sleeps you can do the following:

nr_of_comments = 0

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

while True:
    sleep(10)
    try:
        run_bot()
    except e:
        continue
like image 26
Alu Avatar answered Sep 20 '22 23:09

Alu