spacepy.toolbox.do_with_timeout

spacepy.toolbox.do_with_timeout(timeout, target, *args, **kwargs)[source]

Execute a function (or method) with a timeout.

Call the function (or method) target, with arguments args and keyword arguments kwargs. Normally return the return value from target, but if target takes more than timeout seconds to execute, raises TimeoutError.

Note

This is, at best, a blunt instrument. Exceptions from target may not propagate properly (tracebacks will be hard to follow.) The function which failed to time out may continue to execute until the interpreter exits; trapping the TimeoutError and continuing normally is not recommended.

Parameters:
timeoutfloat

Timeout, in seconds.

targetcallable
Python callable (generally a function, may also be an

imported ctypes function) to run.

argssequence

Arguments to pass to target.

kwargsdict

keyword arguments to pass to target.

Returns:
out

return value of target

Raises:
TimeoutError

If target does not return in timeout seconds.

Examples

>>> import spacepy.toolbox as tb
>>> import time
>>> def time_me_out():
...     time.sleep(5)
>>> tb.do_with_timeout(0.5, time_me_out) #raises TimeoutError