Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catching "socket.timeout The read operation timed out" in python

I'm making calls to an API and am receiving the following timeout error:

socket.timeout The read operation timed out

which traces back from

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

How can I catch this error from the top of the traceback?

like image 269
jjjjjj Avatar asked Aug 19 '17 16:08

jjjjjj


People also ask

How do you fix timeout error in Python?

In Python, use the stdin. readline() and stdout. write() instead of input and print. Ensure that the input value to test cases is passed in the expected format.

Why does socket read timed out?

From the client side, the “read timed out” error happens if the server is taking longer to respond and send information. This could be due to a slow internet connection, or the host could be offline.

How do I increase the socket timeout in Python?

The typical approach is to use select() to wait until data is available or until the timeout occurs. Only call recv() when data is actually available. To be safe, we also set the socket to non-blocking mode to guarantee that recv() will never block indefinitely.

What is socket timeout Python?

Socket connection timeout High A new Python socket by default doesn't have a timeout. Its timeout defaults to None. Not setting the connection timeout parameter can result in blocking socket mode. In blocking mode, operations block until complete or the system returns an error.


1 Answers

This is a duplicate question, however the correct approach is to catch socket.timeout by using

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

The error states the exception that was thrown explicitly and you can rely on that. Even though the calling method is the ssl lib, the error seems to be related to the actual socket connection.

like image 108
Serubin Avatar answered Sep 19 '22 00:09

Serubin