0

I'm attempting to code a try-except loop that refreshes a webpage if it fails to load. Here's what I've done so far:

driver.get("url")

while True:
    try:
        <operation>
    except:
        driver.refresh()

I want to set this loop up so that if 5 seconds elapse and the operation is not executed (presumably because the page did not load), it attempts to refresh the page. Is there an exception we can incorporate in except that catches the time delay?

user3294195
  • 1,748
  • 1
  • 19
  • 36
  • See here: http://stackoverflow.com/questions/8616630/time-out-decorator-on-a-multprocessing-function – ebarr Mar 30 '14 at 09:06

1 Answers1

0

I would recommend reading this post Timeout function if it takes too long to finish.

The gist of it is that you can use signals to interrupt the code and raise an error, which you then catch.

In you example:

def _handle_timeout(signum,frame):
    raise TimeoutError("Execution timed out")

driver.get("url")
signal.signal(signal.SIGALRM, _handle_timeout)   

while True:
    try:
        signal.alarm(<timeout value>)
        <operation>
        signal.alarm(0) 
    except:
        driver.refresh()

You can test this with the following snippet:

import time
import signal

def _handle_timeout(signum,frame):
    raise TimeoutError("Execution timed out")

def test(timeout,execution_time):
    signal.signal(signal.SIGALRM, _handle_timeout)
    try:
        signal.alarm(timeout)
        time.sleep(execution_time)
        signal.alarm(0)
    except:
        raise
    else:
    print "Executed successfully"

This will raise an error when execution_time > timeout.

As noted here in Python signal don't work even on Cygwin? the above code will not work on windows machines.

Community
  • 1
  • 1
ebarr
  • 7,704
  • 1
  • 29
  • 40
  • Thanks, this makes sense. However, I'm not able to get signal.SIGALRM to function on Python 3.3.4. I get `AttributeError: 'module' object has no attribute 'SIGALRM'` – user3294195 Mar 30 '14 at 09:59
  • Added a line to the answer, as this is an important point for others too. – ebarr Mar 30 '14 at 10:24
  • Also, this blog post is required reading on the subject: http://eli.thegreenplace.net/2011/08/22/how-not-to-set-a-timeout-on-a-computation-in-python/ – ebarr Mar 30 '14 at 10:34