stopit: Timeout Control for Python

1.1.2 · maintenance · verified Thu Apr 16

stopit is a Python library that provides flexible mechanisms for controlling the execution time of code blocks and functions. It offers both context managers and decorators to enforce timeouts and can raise exceptions in other threads. The current version is 1.1.2, with its last major update in 2018, indicating a maintenance-focused release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates using `stopit.ThreadingTimeout` as a context manager and `stopit.threading_timeoutable` as a decorator to limit the execution time of code. The context manager allows checking its state to determine if execution completed or timed out. The decorator automatically returns a default value if the function exceeds its allowed time.

import stopit
import time

print("Starting long running task with 5-second timeout...")
with stopit.ThreadingTimeout(5) as context_manager:
    # Simulate a long-running operation
    for i in range(10**8):
        _ = i * 2 # Some computation
        if not context_manager.state == context_manager.EXECUTING: # Optional: check state inside loop
            break

if context_manager.state == context_manager.EXECUTED:
    print("Task completed within timeout.")
elif context_manager.state == context_manager.TIMED_OUT:
    print("Task timed out after 5 seconds.")

# Example using a decorator
@stopit.threading_timeoutable(default='Timed out!')
def potentially_long_function(timeout=1, max_iterations=10**8):
    print(f"  Function starting with {timeout}s timeout...")
    for i in range(max_iterations):
        _ = i * 2
        time.sleep(0.001) # Small sleep to allow thread context switching
    return "Function completed."

result = potentially_long_function(timeout=2)
print(f"Decorator result: {result}")

result_fast = potentially_long_function(timeout=10, max_iterations=1000)
print(f"Decorator result (fast completion): {result_fast}")

view raw JSON →