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 | |
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 | |
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 | |
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 | |