我有一个关于 Python 2.7 的问题。该urlopen
功能有时会因网络状况不佳而无法连接。所以我想在它上面加一个定时器,这样当连接超时时,它会关闭之前的连接并尝试重新连接。在我的实现中,它会陷入死循环,一次又一次地“尝试重新连接”......有人可以帮我吗?非常感谢你!
def getConnection(urlItem, keywords, address):
urlItem.close()
print "Trying to reconnect..."
findArticles(keywords, address)
def findArticles(keywords, address):
urlItem = urllib.urlopen(address)
t = Timer(20.0, getConnection(urlItem, keywords, address))
t.start()
htmlSource = urlItem.read()
t.cancel()
这是我得到的例外:
File "/usr/lib/python2.7/urllib.py", line 84, in urlopen
return opener.open(url)
File "/usr/lib/python2.7/urllib.py", line 205, in open
return getattr(self, name)(url)
File "/usr/lib/python2.7/urllib.py", line 342, in open_http
h.endheaders(data)
File "/usr/lib/python2.7/httplib.py", line 951, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 811, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 773, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 754, in connect
self.timeout, self.source_address)
File "/usr/lib/python2.7/socket.py", line 553, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
IOError: [Errno socket error] [Errno -2] Name or service not known