Timeout Decorator

0.5.0 · active · verified Fri Apr 10

The `timeout-decorator` library provides a simple Python decorator to enforce execution time limits on functions. It primarily uses Unix signals for timeouts in the main thread but offers a multiprocessing strategy for use in other threads or on Windows. The library is currently at version 0.5.0, with its last release in 2020, but it remains a commonly used solution for function timeouts.

Warnings

Install

Imports

Quickstart

This example demonstrates basic usage with both the default signal-based timeout and the multiprocessing strategy. The `long_running_function` will time out after 5 seconds using signals, while `another_long_running_function` will time out after 3 seconds using the multiprocessing approach, useful for non-main threads or Windows.

import time
import timeout_decorator

@timeout_decorator.timeout(5)
def long_running_function():
    print("Starting long_running_function...")
    for i in range(1, 10):
        time.sleep(1)
        print(f"{i} seconds have passed inside function")
    print("long_running_function completed.")

@timeout_decorator.timeout(3, use_signals=False)
def another_long_running_function():
    print("Starting another_long_running_function with multiprocessing strategy...")
    for i in range(1, 10):
        time.sleep(1)
        print(f"{i} seconds have passed inside function")
    print("another_long_running_function completed.")

if __name__ == '__main__':
    print("--- Testing signal-based timeout ---")
    try:
        long_running_function()
    except timeout_decorator.TimeoutError:
        print("long_running_function timed out after 5 seconds.")
    print("\n--- Testing multiprocessing-based timeout ---")
    try:
        another_long_running_function()
    except timeout_decorator.TimeoutError:
        print("another_long_running_function timed out after 3 seconds.")

view raw JSON →