Python 2.6之前版本中urllib2.urlopen()的超时
声明超时参数是在Python2.6中添加的。不幸的是,我的代码库一直在Python 2.5和2.4平台上运行 是否有其他方法来模拟超时?我所要做的就是允许代码在固定时间内与远程服务器通信Python 2.6之前版本中urllib2.urlopen()的超时,python,urllib2,urlopen,Python,Urllib2,Urlopen,声明超时参数是在Python2.6中添加的。不幸的是,我的代码库一直在Python 2.5和2.4平台上运行 是否有其他方法来模拟超时?我所要做的就是允许代码在固定时间内与远程服务器通信 也许有其他的内置库吗?(不想安装第三方,比如pycurl)我认为最好的选择是使用 该文件应位于/usr/lib/python2.4/urllib2.py(在linux和2.4上)我使用标准库中的httplib。它有一个非常简单的API,但正如您可能猜到的那样,它只处理http。IIUC urllib使用http
也许有其他的内置库吗?(不想安装第三方,比如pycurl)我认为最好的选择是使用
该文件应位于
/usr/lib/python2.4/urllib2.py
(在linux和2.4上)我使用标准库中的httplib。它有一个非常简单的API,但正如您可能猜到的那样,它只处理http。IIUC urllib使用httplib实现http功能。您可以使用以下命令为所有套接字操作(包括http请求)设置全局超时:
像这样:
import urllib2
import socket
socket.setdefaulttimeout(30)
f = urllib2.urlopen('http://www.python.org/')
在这种情况下,urllib2请求将在30秒后超时,并引发套接字异常。(这是在Python2.3中添加的)那么,在2.4或2.6中处理超时的方式是相同的。如果在2.6 u中打开urllib2.py文件,将看到它接受一个额外的参数作为超时,并使用socket.defaulttimeout()方法处理它,如答案1所述
因此,在这种情况下,您确实不需要更新您的urllib2.py。非常恼火的是,您可以覆盖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)
必须在两个位置设置超时
import urllib2
import socket
socket.setdefaulttimeout(30)
f = urllib2.urlopen('http://www.python.org/', timeout=30)
socket.settimeout()呢?这会有帮助吗?我想可能吧,我很久以前也遇到过同样的问题,由于某种原因我无法让它工作。但是,我不记得代码可能在哪里,因此无法检查:/httplib仅在2.6版本中支持超时,这两个版本可以独立工作。然而,timeout=30本身可以工作。这对我来说是最好的答案,所以我删除了你的-1。如果您将答案标题改为“您可以选择在一个或两个位置设置超时”。主要问题还涉及Python版本的问题。
在Python3.0中,urllib2模块被拆分为几个模块,分别命名为urllib.request和urllib.error。
但其余代码足够简单。