File: ossignal.py

package info (click to toggle)
python-scrapy 2.13.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,664 kB
  • sloc: python: 52,028; xml: 199; makefile: 25; sh: 7
file content (38 lines) | stat: -rw-r--r-- 1,300 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from __future__ import annotations

import signal
from collections.abc import Callable
from types import FrameType
from typing import Any, Optional, Union

# copy of _HANDLER from typeshed/stdlib/signal.pyi
SignalHandlerT = Union[
    Callable[[int, Optional[FrameType]], Any], int, signal.Handlers, None
]

signal_names: dict[int, str] = {}
for signame in dir(signal):
    if signame.startswith("SIG") and not signame.startswith("SIG_"):
        signum = getattr(signal, signame)
        if isinstance(signum, int):
            signal_names[signum] = signame


def install_shutdown_handlers(
    function: SignalHandlerT, override_sigint: bool = True
) -> None:
    """Install the given function as a signal handler for all common shutdown
    signals (such as SIGINT, SIGTERM, etc). If ``override_sigint`` is ``False`` the
    SIGINT handler won't be installed if there is already a handler in place
    (e.g. Pdb)
    """
    signal.signal(signal.SIGTERM, function)
    if (
        signal.getsignal(signal.SIGINT)  # pylint: disable=comparison-with-callable
        == signal.default_int_handler
        or override_sigint
    ):
        signal.signal(signal.SIGINT, function)
    # Catch Ctrl-Break in windows
    if hasattr(signal, "SIGBREAK"):
        signal.signal(signal.SIGBREAK, function)