There is no TimeoutException
exception type in either the Python 2 or Python 3 standard libraries. In Python 3.3 and newer, there is a TimeoutError
type which is raised when an operating system call times out in the system (corresponding to errno
being set to the ETIMEDOUT
value). However, I do not recommend you raise this value yourself, due to its specific intent of being raised in response to timeouts returned by the operating system.
Correct use of signal.signal
In your comment, after defining a custom timeout exception type, you indicate a further error arises: handler() takes exactly 1 argument (2 given)
.
This occurs because your signal handler does not adhere to the definition of a signal handler function as expected by the signal
package (those docs for Python 3, but identical to Python 2):
signal.signal(signum, handler)
Set the handler for signal signalnum to the function handler... The handler is called with two arguments: the signal number and the current stack frame
To remedy this, adjust the definition of your custom signal handler to receive the stack frame as the second argument. You need to accept this in the function call, as the standard library expects, but you don't need to do anything with the value passed in.
def handler(signum, frame):
raise TimeoutException("Timeout occurred!")
Better way? Use socket.settimeout
There is built-in support in the socket
library for what you are trying to accomplish: the settimeout
method of socket objects. I would recommend using this in your code, rather than attempting to reinvent the wheel; it declares intent while abstracting away the details of the implementation and has a built-in exception type (socket.timeout
) you can catch to determine when timeouts occur.
Using this method, you would simply call socket.settimeout(5)
on your socket prior to making blocking calls which may timeout. You can also set a default timeout on all sockets using socket.setdefaulttimeout
before opening the first socket in the application.
Where did TimeoutException
come from originally?
Obviously, your use of this may have originated from anywhere. However, I note there is a TimeoutException
in Selenium, which is a widely-used Python library used for automating browsers. It is widely used and examples/Q&A associated with Selenium is common, so I would not be surprised if you had found documentation or examples which led you to believe this was an exception type present in the standard library whereas it is actually a type specific to that library. It does not appear that anything related to Selenium is applicable to your present usecase.