On this page
signal
Prev: shutil | Up: stdlib_module | Next: site
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — signal
Tags: #public #python3 #stdlib
Import
import signal
Overview
Installs handlers for asynchronous OS signals (SIGINT, SIGTERM, SIGHUP, SIGWINCH) so long-running CLI tools, daemons, and terminal apps can shut down gracefully or react to terminal resizes. Always keep signal handlers minimal (set a flag or threading.Event and return immediately).
Quick Start
import signal
original = signal.getsignal(signal.SIGINT)
assert original is not None
Implementation Walkthrough
1. Graceful Shutdown Handler for Services & Daemons
Catch SIGINT (Ctrl-C) and SIGTERM (container/systemd stop) to flip a stop flag and let your main loop finish cleanup cleanly:
import signal
import threading
stop_event = threading.Event()
def _handle_stop(signum: int, _frame: object) -> None:
stop_event.set()
def install_shutdown_handlers() -> None:
signal.signal(signal.SIGINT, _handle_stop)
if hasattr(signal, "SIGTERM"):
signal.signal(signal.SIGTERM, _handle_stop)
Gotchas & Boundaries
- Signal handlers can ONLY be installed from the main thread: Calling
signal.signal()in a worker thread raisesValueError. - Keep handlers tiny and reentrant-safe: Never acquire a
threading.Lock, perform complex I/O, or log heavily inside a signal handler—just set a boolean orEvent. - In asyncio, use
loop.add_signal_handler(signal.SIGTERM, ...)on Unix instead ofsignal.signal(). SIGKILLandSIGSTOPcannot be caught, blocked, or ignored by any process.
Common Functions
- signal.alarm() —
alarm(seconds, /)— Arrange for SIGALRM to arrive after the given number of seconds. - signal.default_int_handler() —
default_int_handler(signalnum, frame, /)— The default handler for SIGINT installed by Python. - signal.getitimer() —
getitimer(which, /)— Returns current value of given itimer. - signal.getsignal() —
getsignal(signalnum)— Return the current action for the given signal. - signal.pause() —
pause()— Wait until a signal arrives. - signal.pthread_kill() —
pthread_kill(thread_id, signalnum, /)— Send a signal to a thread. - signal.pthread_sigmask() —
pthread_sigmask(how, mask)— Fetch and/or change the signal mask of the calling thread. - signal.raise_signal() —
raise_signal(signalnum, /)— Send a signal to the executing process. - signal.set_wakeup_fd() —
set_wakeup_fd(fd, /, *, warn_on_full_buffer=True)— Sets the fd to be written to (with the signal number) when a signal comes in. - signal.setitimer() —
setitimer(which, seconds, interval=0.0, /)— Sets given itimer (one of ITIMER_REAL, ITIMER_VIRTUAL or ITIMER_PROF). - signal.siginterrupt() —
siginterrupt(signalnum, flag, /)— Change system call restart behaviour. - signal.signal() —
signal(signalnum, handler)— Set the action for the given signal. - signal.sigpending() —
sigpending()— Examine pending signals. - signal.sigwait() —
sigwait(sigset)— Wait for a signal. - signal.strsignal() —
strsignal(signalnum, /)— Return the system description of the given signal. - signal.valid_signals() —
valid_signals()— Return a set of valid signal numbers on this platform.
Classes & Objects
- signal.Handlers — An enumeration. (Methods:
.as_integer_ratio(),.bit_count(),.bit_length(),.conjugate(),.from_bytes(),.is_integer()) - signal.ItimerError —
signal.ItimerErrorclass. (Methods:.add_note(),.with_traceback()) - signal.Sigmasks — An enumeration. (Methods:
.as_integer_ratio(),.bit_count(),.bit_length(),.conjugate(),.from_bytes(),.is_integer()) - signal.Signals — An enumeration. (Methods:
.as_integer_ratio(),.bit_count(),.bit_length(),.conjugate(),.from_bytes(),.is_integer())
Constants & Attributes
signal.ITIMER_PROF(int) =2signal.ITIMER_REAL(int) =0signal.ITIMER_VIRTUAL(int) =1signal.NSIG(int) =32signal.SIGABRT(Signals) =<Signals.SIGABRT: 6>signal.SIGALRM(Signals) =<Signals.SIGALRM: 14>signal.SIGBUS(Signals) =<Signals.SIGBUS: 10>signal.SIGCHLD(Signals) =<Signals.SIGCHLD: 20>signal.SIGCONT(Signals) =<Signals.SIGCONT: 19>signal.SIGEMT(Signals) =<Signals.SIGEMT: 7>signal.SIGFPE(Signals) =<Signals.SIGFPE: 8>signal.SIGHUP(Signals) =<Signals.SIGHUP: 1>signal.SIGILL(Signals) =<Signals.SIGILL: 4>signal.SIGINFO(Signals) =<Signals.SIGINFO: 29>signal.SIGINT(Signals) =<Signals.SIGINT: 2>
Linked from
Related notes
- tuts/python3/stdlib_module/shutil Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/site Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/asyncio Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/atexit links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/getopt Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/io Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/os Linked here; shared tags: #stdlib