Skip to content

signal

Process signal handling with prioritized handler chains.

This module provides utilities for registering multiple signal handlers per signal, ordered by priority. Handlers may return HANDLED to stop chain propagation or CALL_NEXT to continue. The :class:Signals context manager provides scoped handler registration, and state is preserved across process forks via the global namespace module.

The priority determines the dispatch order - lower values run first - and defaults to STD_PRIO (the lowest priority). Note that trigger() manually invokes the registered handlers, and that the signals module owns the OS-level handler for any signal registered through it.

Example
import signal
from py_misc_utils import signal as sgn

hits = []

def handler(sig, frame):
  hits.append(sig)

  return sgn.HANDLED

with sgn.Signals(signal.SIGUSR1, handler):
  sgn.trigger(signal.SIGUSR1)

assert hits == [signal.SIGUSR1]

Signals

Context manager for scoped signal handler registration.

Registers handlers for one or more signals on enter and removes them on exit.

Source code in py_misc_utils/signal.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
class Signals:
  """Context manager for scoped signal handler registration.

  Registers handlers for one or more signals on __enter__ and removes them
  on __exit__.
  """

  def __init__(self, sig, handler, prio=None):
    """Normalize the signals and handlers into aligned tuples.

    Args:
      sig: A signal name ('INT'), a signal number, or a list of them.
      handler: A callable or a list of callables aligned with sig.
      prio: Optional priority (lower runs first).
    """
    if isinstance(sig, str):
      sig = [getattr(sgn, f'SIG{s.upper()}') for s in cu.splitstrip(sig, ',')]
    elif not isinstance(sig, (list, tuple)):
      sig = [sig]
    if not isinstance(handler, (list, tuple)):
      handler = [handler] * len(sig)

    self._sigs = tuple(zip(sig, handler))
    self._prio = prio

  def __enter__(self):
    """Register all signal handlers.

    Returns:
      The Signals instance itself.
    """
    for sig, handler in self._sigs:
      signal(sig, handler, prio=self._prio)

    return self

  def __exit__(self, *exc):
    """Remove all registered signal handlers.

    Args:
      *exc: Exception information if an exception occurred in the context.

    Returns:
      True (exceptions are suppressed).
    """
    for sig, handler in self._sigs:
      unsignal(sig, handler)

    return True

trigger(sig, frame=None)

Manually invoke signal handlers for a signal as if it were received.

Parameters:

Name Type Description Default
sig

The signal number to trigger.

required
frame

Optional stack frame to pass; defaults to the caller's frame.

None
Source code in py_misc_utils/signal.py
199
200
201
202
203
204
205
206
def trigger(sig, frame=None):
  """Manually invoke signal handlers for a signal as if it were received.

  Args:
    sig: The signal number to trigger.
    frame: Optional stack frame to pass; defaults to the caller's frame.
  """
  _handler(sig, frame or tb.get_frame(n=1))

signal(sig, handler, prio=None)

Register a handler for a signal.

Parameters:

Name Type Description Default
sig

The signal number.

required
handler

The callable to invoke when the signal is received.

required
prio

Optional priority (lower runs first); defaults to STD_PRIO.

None
Source code in py_misc_utils/signal.py
209
210
211
212
213
214
215
216
217
218
219
def signal(sig, handler, prio=None):
  """Register a handler for a signal.

  Args:
    sig: The signal number.
    handler: The callable to invoke when the signal is received.
    prio: Optional priority (lower runs first); defaults to STD_PRIO.
  """
  sreg = _sig_registry()

  sreg.signal(sig, handler, prio=prio)

unsignal(sig, uhandler)

Remove a handler for a signal.

Parameters:

Name Type Description Default
sig

The signal number.

required
uhandler

The handler callable to remove.

required

Returns:

Type Description

The number of matching handlers removed.

Source code in py_misc_utils/signal.py
222
223
224
225
226
227
228
229
230
231
232
233
234
def unsignal(sig, uhandler):
  """Remove a handler for a signal.

  Args:
    sig: The signal number.
    uhandler: The handler callable to remove.

  Returns:
    The number of matching handlers removed.
  """
  sreg = _sig_registry()

  return sreg.unsignal(sig, uhandler)