cysignals

1.12.6 · active · verified Thu Apr 16

cysignals is a Python library designed for robust interrupt and signal handling within Cython code. It provides mechanisms to ensure that long-running Cython computations can be interrupted (e.g., via CTRL-C) and offers a Python interface for managing OS-level signal handlers and system calls like `pselect()` and `sigprocmask()`. The library is currently at version 1.12.6, actively maintained by the SageMath community, and receives regular updates to support newer Python and Cython versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core interrupt handling mechanism using `sig_check()`. While `sig_check()` is a Cython cimport, the Python code here illustrates its effect by demonstrating an interruptible long-running loop. In actual use, `sig_check()` would be placed within Cython `def`, `cdef`, or `cpdef` functions to allow graceful interruption. A real-world example would involve compiling a `.pyx` file containing the `cimport` and `sig_check()` calls.

import cython
import os

# This code needs to be in a .pyx file to be compiled by Cython
# For demonstration, we simulate compilation by directly defining in Python context
# In a real scenario, this would be compiled with a setup.py/pyproject.toml

def run_interruptible_loop(n_iterations: int):
    try:
        # In a .pyx file, you would use: from cysignals.signals cimport sig_check
        # For this quickstart, we use a mock for illustration in a .py file
        # In practice, you'd compile this Cython code.
        # This is a simplified representation of how sig_check would be used.

        # Simulate Cython compilation and execution
        print(f"Running a loop for {n_iterations} iterations. Try pressing CTRL+C.")
        for i in range(n_iterations):
            # Imagine this is within a Cython function containing a `sig_check()` call
            if i % 1_000_000 == 0:
                print(f"  Iteration {i}")
            # A real sig_check() would check for interrupts and raise KeyboardInterrupt
            # if os.getenv('CYSIGNALS_SIMULATE_INTERRUPT') and i == n_iterations // 2:
            #     raise KeyboardInterrupt("Simulated interrupt")
            
            # Simulate a small amount of work
            _ = i * i

        print("Loop completed without interruption.")

    except KeyboardInterrupt:
        print("\nLoop interrupted by user (KeyboardInterrupt caught)!")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == '__main__':
    # This part would run the compiled Cython module
    # For this example, we directly call the Python function simulating the loop.
    run_interruptible_loop(10_000_000)

view raw JSON →