InterruptingCow
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
-
AttributeError: 'module' object has no attribute 'GeneratorContextManager'
cause This error occurs when `interruptingcow` attempts to import or use a class (`GeneratorContextManager`) from Python's internal `contextlib` module that was an undocumented implementation detail in Python 2 and removed/changed in Python 3.6+.fixThis library is designed for older Python versions (up to 3.5). Downgrade your Python environment to 3.5 or earlier, or migrate to a different, actively maintained timeout library compatible with modern Python versions. -
My timeout doesn't work when I use threads, or my program hangs.
cause The `interruptingcow` library uses `signal(SIGALRM)` which only works reliably in the main thread of a Python process. Threads created via `threading` module will not receive these signals.fixRefactor your code to execute the timed operation within the main thread, or use an alternative inter-thread communication mechanism (e.g., `threading.Event`, `queue` with a timeout, or `concurrent.futures.wait` with a timeout) if the operation must be performed in a separate thread.
Warnings
- breaking Interruptingcow relies on `signal(SIGALRM)` for interruption, which is a C-level signal and only applies to the main thread in Python. Code running in other threads will not be interrupted by `timeout`.
- breaking The library uses `SIGALRM` and should not be used in programs that also set their own `SIGALRM` handlers. This can lead to unexpected behavior or prevent either the library's timeout or your custom signal handler from working correctly.
- deprecated Version 0.8 explicitly supports Python 2.7 and 3.5. It is known to rely on undocumented internal `contextlib` details (`GeneratorContextManager`) that changed or were removed in Python 3.6+ versions. This can cause `AttributeError` or other import/runtime failures on modern Python environments.
Install
-
pip install interruptingcow
Imports
- timeout
from interruptingcow import timeout
- Quota
from interruptingcow import Quota
Quickstart
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.")