Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The process for timing out an operations is described in the documentation for <a href="http://docs.python.org/library/signal#example" rel="noreferrer">signal</a>.</p> <p>The basic idea is to use signal handlers to set an alarm for some time interval and raise an exception once that timer expires.</p> <p>Note that this will only work on UNIX.</p> <p>Here's an implementation that creates a decorator (save the following code as <code>timeout.py</code>).</p> <pre><code>from functools import wraps import errno import os import signal class TimeoutError(Exception): pass def timeout(seconds=10, error_message=os.strerror(errno.ETIME)): def decorator(func): def _handle_timeout(signum, frame): raise TimeoutError(error_message) def wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _handle_timeout) signal.alarm(seconds) try: result = func(*args, **kwargs) finally: signal.alarm(0) return result return wraps(func)(wrapper) return decorator </code></pre> <p>This creates a decorator called <code>@timeout</code> that can be applied to any long running functions.</p> <p>So, in your application code, you can use the decorator like so:</p> <pre><code>from timeout import timeout # Timeout a long running function with the default expiry of 10 seconds. @timeout def long_running_function1(): ... # Timeout after 5 seconds @timeout(5) def long_running_function2(): ... # Timeout after 30 seconds, with the error "Connection timed out" @timeout(30, os.strerror(errno.ETIMEDOUT)) def long_running_function3(): ... </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload