如何解决Python中catching “socket.timeout The read operation timed out” ?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (1031)

我正在调用API并接收以下超时错误:

socket.timeout The read operation timed out

报错信息:

File "/Users/someuser/anaconda/envs/python3/lib/python3.5/http/client.py", line 1198, in getresponse
    response.begin()
  File "/Users/someuser/anaconda/envs/python3/lib/python3.5/http/client.py", line 297, in begin
    version, status, reason = self._read_status()
  File "/Users/someuser/anaconda/envs/python3/lib/python3.5/http/client.py", line 258, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "/Users/someuser/anaconda/envs/python3/lib/python3.5/socket.py", line 576, in readinto
    return self._sock.recv_into(b)
  File "/Users/someuser/anaconda/envs/python3/lib/python3.5/ssl.py", line 937, in recv_into
    return self.read(nbytes, buffer)
  File "/Users/someuser/anaconda/envs/python3/lib/python3.5/ssl.py", line 799, in read
    return self._sslobj.read(len, buffer)
  File "/Users/someuser/anaconda/envs/python3/lib/python3.5/ssl.py", line 583, in read
    v = self._sslobj.read(len, buffer)
socket.timeout The read operation timed out

如何从跟踪的顶部捕获此错误?

提问于
用户回答回答于

这是一个重复的问题,但是正确的方法是抓住socket.timeout :

try:
    ...
except socket.timeout:
    ...

即使调用方法是SSL库,错误与实际的套接字连接有关

用户回答回答于

似乎ssl抛出ssl.SSLError,当它超时的时候,可以尝试这样的方法:

import ssl

def getresponse():
     ...
     try:
          response.begin
     except ssl.SSLError as err:
          handle_error(err)

扫码关注云+社区

领取腾讯云代金券