我有以下代码已经工作了大约一年:
import urllib2
req = urllib2.Request('https://somewhere.com','')
data = urllib2.urlopen(req)
print data.read()
最近有一些随机的错误:
> urllib2.URLError:< urlopen error [Errno 111]拒绝连接>
>< urlopen错误[Errno 110]连接超时>
失败的痕迹是:
Traceback (most recent call last):
File "test.py", line 4, in
data = urllib2.urlopen(req).read()
File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 400, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 418, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1215, in https_open
return self.do_open(httplib.HTTPSConnection, req)
File "/usr/lib/python2.7/urllib2.py", line 1177, in do_open
raise URLError(err)
urllib2.URLError:
上述错误随机发生,脚本可以首次运行成功,但在第二次运行时失败,反之亦然。
我该怎么办来调试,弄清楚问题出在哪里?如何判断端点是否消耗了我的请求并返回响应,但从未到达我?
用telnet
我只是用telnet测试,有时它成功了,有时它不像我的Python那样。
成功:
$ telnet somewhere.com 443
Trying XXX.YY.ZZZ.WWW...
Connected to somewhere.com.
Escape character is '^]'.
Connection closed by foreign host.
拒绝连接:
$ telnet somewhere.com 443
Trying XXX.YY.ZZZ.WWW...
telnet: Unable to connect to remote host: Connection refused
超时:
$ telnet somewhere.com 443
Trying XXX.YY.ZZZ.WWW...
telnet: Unable to connect to remote host: Connection timed out