0

我有一个关于 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
4

1 回答 1

0

旧的 urllib 库本身不支持设置超时,但urllib2支持。您应该考虑使用 urllib2,也就是说...

您可以导入套接字并在所有新创建的套接字上设置默认超时。这可能是一种迂回的方式来做你需要做的事情。

http://docs.python.org/2.7/library/socket.html#socket.setdefaulttimeout

于 2013-06-13T20:37:01.407 回答