2017-01-20 47 views
1

我目前正在编写一个Python 2.7程序,它使用Mechanize来查询某个网站的一些URL信息。伪码是这样的:10秒后停止阻止操作?

for URL in urls: 
    # first submit a form to query the URL... 
    # then wait and parse the results: 
    while 1: 
     content = response.read(1024) 
     # followed by some other simple parsing operations ... 

读()操作在while循环1是一个阻塞,并且由于网络和其他条件,有时它运行下去。我试图实现的是停止等待read()并跳转到查询下一个URL,如果当前的read()操作在10秒后没有返回。如何计时read()操作并查看content在10秒后是否为空?我正在考虑使用线程,但不知道如何继续。谁能帮忙?提前致谢!

+2

使用'select' .... –

+0

我猜你正在使用的urllib2?看到这个答案:http://stackoverflow.com/questions/16646322/setting-the-timeout-on-a-urllib2-request-call –

+0

@MikePlacentra对不起,我刚刚更新我的帖子,我使用机械化,而不是urllib2。谢谢 – fittaoee

回答

1

尝试使用在此所说明的超时装饰 - https://pypi.python.org/pypi/timeout-decorator

+0

谢谢。我尝试了该页面上的示例代码,但它似乎会引发异常并在发生超时时暂停程序。有没有办法阻止它在超时时引发异常并暂停程序? – fittaoee

+0

'尝试'和'除了timeout_decorator.TimeoutError' – sberry

+0

您可以处理异常并继续执行其余程序,如下所示:

 'try: mytest() except timeout_decorator.TimeoutError as te: # do more' 
或者您可以分叉github回购(需要授权)并自定义[code] (https://github.com/pnpnpn/timeout-decorator/blob/master/timeout_decorator/timeout_decorator.py)@行#144不会引发异常,但可能会重试? – KMeansK