Search code examples
pythonexceptiontimeouthandlepraw

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

Solution

  • 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