InterruptingCow

0.8 · maintenance · verified Thu Apr 16

Interruptingcow is a generic utility designed to gracefully interrupt Python code that exceeds a specified execution time. It achieves this by utilizing the `signal(SIGALRM)` mechanism. The current version is 0.8, with an infrequent release cadence, as the last update was in 2018.

Common errors

Warnings

Install

Imports

Quickstart

The primary use case is wrapping potentially long-running code in a `with timeout(...)` block. If the code inside the block exceeds the specified time, a `RuntimeError` (or a custom exception) is raised. Quotas can be used to limit total time across multiple calls.

import time
from interruptingcow import timeout

try:
    with timeout(2, exception=RuntimeError):
        print("Starting a 3-second operation...")
        time.sleep(3)
        print("Operation completed.") # This line will not be reached
except RuntimeError:
    print("Operation didn't finish within 2 seconds.")

# Example with quota
from interruptingcow import Quota
quota = Quota(1.0)

for i in range(5):
    try:
        with timeout(quota, RuntimeError):
            print(f"Iteration {i+1}: Performing expensive operation...")
            time.sleep(0.3) # Each takes 0.3s
    except RuntimeError:
        print(f"Iteration {i+1}: Quota exceeded for expensive operation, doing cheaper thing.")

view raw JSON →