超时urllib2.urlopen()前期的Python 2.6版本
题
在的urllib2文档说超时的溶液中加入参数在Python 2.6。不幸的是我的代码基础已经关于Python 2.5和2.4的平台上运行。
是否有模拟超时任何替代方式是什么?所有我想要做的是使代码交谈远程服务器用于一个固定的时间量。
也许任何替代内置库? (不想安装第三方,像pycurl)
解决方案
可以通过使用设置所有插座操作(包括HTTP请求)一个全局超时:
是这样的:
import urllib2
import socket
socket.setdefaulttimeout(30)
f = urllib2.urlopen('http://www.python.org/')
在这种情况下,你的urllib2的要求会后30秒超时并抛出一个插座例外。 (这是在Python 2.3增加)
其他提示
使用相当大的刺激,可以覆盖该urllib2.HTTPHandler使用httplib.HTTPConnection类。
def urlopen_with_timeout(url, data=None, timeout=None):
# Create these two helper classes fresh each time, since
# timeout needs to be in the closure.
class TimeoutHTTPConnection(httplib.HTTPConnection):
def connect(self):
"""Connect to the host and port specified in __init__."""
msg = "getaddrinfo returns an empty list"
for res in socket.getaddrinfo(self.host, self.port, 0,
socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
if timeout is not None:
self.sock.settimeout(timeout)
if self.debuglevel > 0:
print "connect: (%s, %s)" % (self.host, self.port)
self.sock.connect(sa)
except socket.error, msg:
if self.debuglevel > 0:
print 'connect fail:', (self.host, self.port)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
class TimeoutHTTPHandler(urllib2.HTTPHandler):
http_request = urllib2.AbstractHTTPHandler.do_request_
def http_open(self, req):
return self.do_open(TimeoutHTTPConnection, req)
opener = urllib2.build_opener(TimeoutHTTPHandler)
opener.open(url, data)
我觉得你最好的选择是修补(或部署的本地版本),你用的urllib2的从2.6维护分支中的变化
在文件应在/usr/lib/python2.4/urllib2.py
(Linux和2.4)
我用httplib的标准库。它有一个死了简单的API,但只能处理HTTP您可能已经猜到。 IIUC的urllib使用httplib的实现HTTP东西。
您必须在两个地方设置超时。
import urllib2
import socket
socket.setdefaulttimeout(30)
f = urllib2.urlopen('http://www.python.org/', timeout=30)
那么,超时的方式在任一2.4或2.6处理是相同的。如果您在2.6打开urllib2.py文件ü会看到,它需要一个额外的参数如超时,并使用socket.defaulttimeout()方法提到的答案1。
处理它所以,你真的不必更新在这种情况下你urllib2.py。
不隶属于 StackOverflow