2014-03-30 63 views
0

我试图编写一个try-except循环,刷新网页,如果无法加载。这是我到目前为止已经完成:Python - Try-except循环 - 引用时间延迟作为例外

driver.get("url") 

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

我想,这样如果在5秒内,并且不执行操作(大概是因为页面没有加载),它试图刷新设置这个循环起来页。是否有例外,我们可以纳入except捕捉时间延迟?

+0

请参阅:http://stackoverflow.com/questions/8616630/time-out-decorator-on-a-multprocessing-function – ebarr

回答

0

我会推荐阅读这篇文章Timeout function if it takes too long to finish

它的要点是你可以使用信号来中断代码并产生一个错误,然后你就可以捕获它。

在您例如:

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() 

你可以用下面的代码片段测试:

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" 

这将提高时错误execution_time > timeout

正如Python signal don't work even on Cygwin?中所述,上述代码在Windows机器上不起作用。

+0

谢谢,这是有道理的。但是,我无法获取signal.SIGALRM在Python 3.3.4上运行。我得到'AttributeError:'模块'对象没有属性'SIGALRM'' – user3294195

+0

在答案中增加了一行,因为这对其他人来说也是一个重要的点。 – ebarr

+0

此外,这篇博客文章是必读的主题:http://eli.thegreenplace.net/2011/08/22/how-not-to-set-a-timeout-on-a-computation-in-python / – ebarr