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.