While socket.setsocketimeout
将为新套接字设置默认超时,如果您不直接使用套接字,则可以轻松覆盖该设置。特别是,如果库调用socket.setblocking
在其套接字上,它将重置超时。
urllib2.open
有超时参数,但是,没有超时urllib2.Request
。当你使用mechanize
,你应该参考他们的文档:
从 Python 2.6 开始,urllib2 在内部使用 Request 对象的 .timeout 属性。但是,urllib2.Request 没有超时构造函数参数,并且 urllib2.urlopen() 忽略此参数。 mechanize.Request 有一个超时构造函数参数,用于设置同名属性,mechanize.urlopen() 不会忽略超时属性。
source: http://wwwsearch.sourceforge.net/mechanize/documentation.html http://wwwsearch.sourceforge.net/mechanize/documentation.html
- -编辑 - -
如果其中之一socket.setsockettimeout
或将超时传递给mechanize
适用于较小的值,但不适用于较高的值,问题的根源可能完全不同。有一件事是你的库可能会打开多个连接(这里归功于@Cédric Julien),因此超时适用于每次尝试socket.open,如果它没有因第一次失败而停止 - 可能需要长达timeout * num_of_conn
秒。另一件事是socket.recv
:如果连接真的很慢并且您很不幸,整个请求可能需要长达timeout * incoming_bytes
与每个socket.recv
我们可以得到一个字节,并且每个这样的调用都可以花费timeout
秒。由于您不太可能遭受这种黑暗的场景(每个超时秒一个字节?您必须是一个非常粗鲁的男孩),因此很可能需要花费很长时间才能获得非常慢的连接和非常高的超时。
您唯一的解决方案是强制整个请求超时,但这里与套接字无关。如果你使用的是 Unix,你可以使用简单的解决方案ALARM
信号。您设置要发出的信号timeout
秒,您的请求将被终止(不要忘记捕获它)。您可能喜欢使用with
声明使其干净且易于使用,例如:
import signal, time
def request(arg):
"""Your http request"""
time.sleep(2)
return arg
class Timeout():
"""Timeout class using ALARM signal"""
class Timeout(Exception): pass
def __init__(self, sec):
self.sec = sec
def __enter__(self):
signal.signal(signal.SIGALRM, self.raise_timeout)
signal.alarm(self.sec)
def __exit__(self, *args):
signal.alarm(0) # disable alarm
def raise_timeout(self, *args):
raise Timeout.Timeout()
# Run block of code with timeouts
try:
with Timeout(3):
print request("Request 1")
with Timeout(1):
print request("Request 2")
except Timeout.Timeout:
print "Timeout"
# Prints "Request 1" and "Timeout"
如果想要比这更便携,你必须使用一些更大的枪,例如multiprocessing
,因此您将生成一个进程来调用您的请求并在过期时终止它。由于这将是一个单独的过程,您必须使用某些东西将结果传输回您的应用程序,它可能是multiprocessing.Pipe
。下面是例子:
from multiprocessing import Process, Pipe
import time
def request(sleep, result):
"""Your http request example"""
time.sleep(sleep)
return result
class TimeoutWrapper():
"""Timeout wrapper using separate process"""
def __init__(self, func, timeout):
self.func = func
self.timeout = timeout
def __call__(self, *args, **kargs):
"""Run func with timeout"""
def pmain(pipe, func, args, kargs):
"""Function to be called in separate process"""
result = func(*args, **kargs) # call func with passed arguments
pipe.send(result) # send result to pipe
parent_pipe, child_pipe = Pipe() # Pipe for retrieving result of func
p = Process(target=pmain, args=(child_pipe, self.func, args, kargs))
p.start()
p.join(self.timeout) # wait for prcoess to end
if p.is_alive():
p.terminate() # Timeout, kill
return None # or raise exception if None is acceptable result
else:
return parent_pipe.recv() # OK, get result
print TimeoutWrapper(request, 3)(1, "OK") # prints OK
print TimeoutWrapper(request, 1)(2, "Timeout") # prints None
如果您想强制请求在固定秒数后终止,您实际上没有太多选择。socket.timeout
将为单个套接字操作(连接/接收/发送)提供超时,但如果您有多个套接字,您可能会遭受很长的执行时间。