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 argumentsargs
and keyword argumentskwargs
. Normally return the return value fromtarget
, but iftarget
takes more thantimeout
seconds to execute, raisesTimeoutError
.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 intimeout
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