Pebble

5.2.0 · active · verified Sat Apr 11

Pebble is a Python library that enhances `concurrent.futures` with features like timeouts, remote process tracebacks, and cleaner pool management, making threading and multiprocessing more robust and user-friendly. It is currently at version 5.2.0 and maintains an active release cadence with frequent minor updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use Pebble's `ProcessPool` to execute functions in separate processes with built-in timeouts. It covers scheduling tasks, retrieving results, and handling `TimeoutError` as well as other exceptions. The `if __name__ == '__main__':` block is crucial for `ProcessPool` on Windows and macOS.

from pebble import ProcessPool
from concurrent.futures import TimeoutError
import os
import time

def my_task(data, delay):
    # Simulate some work
    time.sleep(delay)
    return f"Processed {data} after {delay}s on PID {os.getpid()}"

if __name__ == "__main__": # Essential for ProcessPool on Windows/macOS
    print("--- Pebble ProcessPool Quickstart ---")
    with ProcessPool(max_workers=2) as pool:
        print("Submitting tasks...")
        # schedule returns a future object, allowing timeout directly on the task
        future1 = pool.schedule(my_task, args=("task A", 1), timeout=2)
        future2 = pool.schedule(my_task, args=("task B", 3), timeout=2) # This task will intentionally timeout

        print("\nGetting results for task 1 (should succeed):")
        try:
            result1 = future1.result() # blocks until result is ready or timeout/exception
            print(f"Result 1: {result1}")
        except TimeoutError:
            print("Task 1 timed out!")
        except Exception as e:
            print(f"Task 1 raised an unexpected exception: {e}")
            # For remote exceptions, e.traceback can provide the remote stack trace

        print("\nGetting results for task 2 (should timeout):")
        try:
            result2 = future2.result()
            print(f"Result 2: {result2}")
        except TimeoutError:
            print("Task 2 timed out as expected!")
        except Exception as e:
            print(f"Task 2 raised an unexpected exception: {e}")
            # For remote exceptions, e.traceback can provide the remote stack trace

    print("\nAll tasks completed or processed in pool.")

view raw JSON →