Python Glossary Русский

all Python 3signalfunction

signal.signal()

handlers

Installs a signal handler and returns the previous one. The handler is a function (signum, frame) or SIG_IGN / SIG_DFL.

Syntax

old = signal.signal(signalnum, handler)

It may only be called from the main thread of the main interpreter — another thread gets ValueError — and the handler itself always runs in the main thread, not instantly but between bytecode instructions. A long call inside C code (a regex over a huge text) will not be interrupted by it. Keep the previous handler and restore it: signal.signal returns it for exactly that reason. On Windows only SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM and SIGBREAK are accepted, and SIGKILL and SIGSTOP cannot be caught anywhere — OSError.

Examples

import signal
got = []
old = signal.signal(signal.SIGTERM, lambda signum, frame: got.append(signum))
signal.raise_signal(signal.SIGTERM)
print(got == [signal.SIGTERM])  # → True — процесс не завершился, сработал обработчик
signal.signal(signal.SIGTERM, old)  # вернуть как было
import signal, threading
def worker():
    try:
        signal.signal(signal.SIGINT, signal.SIG_IGN)
    except ValueError as e:
        print(e)  # → signal only works in main thread of the main interpreter
t = threading.Thread(target=worker)
t.start()
t.join()

See also

Open in the full glossarydocs.python.orgReport an inaccuracy