timeout

(function from pyomo.common.unittest)

pyomo.common.unittest.timeout(seconds, require_fork=False, timeout_raises=<class 'TimeoutError'>)[source]

Function decorator to timeout the decorated function.

This decorator will wrap a function call with a timeout, returning the result of the wrapped function. The timeout is implemented using multiprocessing to execute the function in a forked process. If the wrapped function raises an exception, then the exception will be re-raised in this process. If the function times out, a TimeoutError will be raised.

Note that as this method uses multiprocessing, the wrapped function should NOT spawn any subprocesses. The timeout is implemented using multiprocessing.Process.terminate(), which sends a SIGTERM signal to the subprocess. Any spawned subprocesses are not collected and will be orphaned and left running.

Parameters:
  • seconds (float) – Number of seconds to wait before timing out the function

  • require_fork (bool) – Require support of the ‘fork’ interface. If not present, immediately raises unittest.SkipTest

  • timeout_raises (Exception) – Exception class to raise in the event of a timeout

Examples

>>> import pyomo.common.unittest as unittest
>>> @unittest.timeout(1)
... def test_function():
...     return 42
>>> test_function()
42
>>> @unittest.timeout(0.01)
... def test_function():
...     while 1:
...         pass
>>> test_function()
Traceback (most recent call last):
    ...
TimeoutError: test timed out after 0.01 seconds