interruptingcow /

Filename Size Date modified Message
interruptingcow
tests
31 B
1.1 KB
19 B
1.9 KB
1.2 KB

Interrupting Cow

Interruptingcow is a generic utility can relatively gracefully interrupt your Python code when it doesn't execute within a specific number of seconds:

from interruptingcow import timeout

try:
    with timeout(5, exception=RuntimeError):
        # perform a potentially very slow operation
        pass
except RuntimeError:
    print "didn't finish within 5 seconds"

Timeouts are specified in seconds (as floats with theoretical microsecond precision).

Installation

$ pip install interruptingcow

Reentrant

Interruptingcow is fully reentrant, which means that you can have nested timeouts:

from interruptingcow import timeout

class Outer(RuntimeError): pass

class Inner(RuntimeError): pass

try:
    with timeout(20.0, Outer):
        try:
            with timeout(1.0, Inner):
                # some expensive operation
                try_the_expensive_thing()
        except Inner:
            do_the_cheap_thing_instead()

except Outer:
    print 'Program as a whole failed to return in 20 secs'

Nested timeouts allow a large outer timeout to contain smaller timeouts. If the inner timeout is larger than the outer timeout, it is treated as a no-op.

Function Decorators

Interruptingcow can be used both as inline with-statements, as shown in the above examples, as well as function decorator:

from interruptingcow import timeout

@timeout(.5)
def foo():
    with timeout(.3):
        # some expensive operation
        pass

Caveats

Interruptingcow uses signal(SIGALRM) to let the operating system interrupt program execution. This has the following limitations:

  1. Python signal handlers only apply to the main thread, so you cannot use this from other threads
  2. You must not use this in a program that uses SIGALRM itself (this includes certain profilers)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.