Signals in Python

Handle Ctrl+C and SIGTERM cleanly, and send your own events between parts of an app.

"Python signals" means two unrelated things. One is operating system signals, such as the SIGINT your program gets when someone presses Ctrl+C. The other is in-app signals: one part of your code announcing an event that other parts listen for, as in Django or Blinker. This page covers both, starting with the OS kind.

The short answer

For OS signals, use the signal module from the standard library. Register a function, and Python calls it when the signal arrives:

import signal

shutting_down = False


def handle_shutdown(signum, frame):
    global shutting_down
    shutting_down = True
    print(f"got {signal.Signals(signum).name}, finishing up")


signal.signal(signal.SIGINT, handle_shutdown)
signal.signal(signal.SIGTERM, handle_shutdown)

The handler takes two arguments: the signal number and the stack frame that was running when it arrived. Most handlers ignore the frame.

You can test a handler without killing anything. signal.raise_signal delivers a signal to your own process, and because a handler is installed, the handler runs and the program carries on:

signal.raise_signal(signal.SIGTERM)   # got SIGTERM, finishing up
shutting_down                         # True

SIGINT, SIGTERM and a graceful shutdown

Two signals cover nearly every case:

  • SIGINT is Ctrl+C in a terminal. With no handler of your own, Python raises KeyboardInterrupt.
  • SIGTERM is the polite "please stop" that kill, Docker, systemd and Kubernetes send. With no handler, the process dies on the spot, without running finally blocks.

A graceful shutdown means finishing the current piece of work before exiting. Keep the handler tiny, have it set a flag, and let the main loop check the flag:

import time

while not shutting_down:
    process_next_job()
    time.sleep(1)

close_connections()
print("stopped cleanly")

Doing real work inside the handler is risky, because it can interrupt your code at any point, including halfway through a write. Setting a flag is always safe.

Three limits to know about:

  • signal.signal can only be called from the main thread.
  • SIGKILL (kill -9) cannot be caught. Nothing you write will run.
  • Windows supports only a handful of signals. SIGINT works; SIGTERM handling is not something to rely on there.

To put Ctrl+C back to normal afterwards:

signal.signal(signal.SIGINT, signal.default_int_handler)

In-app signals

The second meaning has nothing to do with the operating system. A signal here is a named event inside your program. One piece of code sends it, and any number of receivers that connected earlier get called. Django uses this for things like post_save, so that saving a model can trigger code in another app without the two importing each other.

The core of it is small enough to write yourself:

class Signal:
    def __init__(self):
        self.receivers = []

    def connect(self, receiver):
        self.receivers.append(receiver)
        return receiver

    def send(self, sender, **kwargs):
        return [receiver(sender, **kwargs) for receiver in self.receivers]


order_paid = Signal()


@order_paid.connect
def send_receipt(sender, order_id, **kwargs):
    return f"receipt sent for order {order_id}"


@order_paid.connect
def update_stock(sender, order_id, **kwargs):
    return f"stock updated for order {order_id}"


order_paid.send("checkout", order_id=42)

connect returns the receiver so it works as a decorator. send passes along who sent the signal plus any keyword arguments, and collects what the receivers return. Receivers accept **kwargs so that adding a new argument later does not break them.

Python Blinker

Blinker is the library version of that class, and it is what Flask uses for its own signals. It adds named signals you can look up from anywhere, receivers that only listen to one sender, and weak references so a connected receiver does not keep an object alive.

from blinker import signal

order_paid = signal("order-paid")


@order_paid.connect
def send_receipt(sender, **kwargs):
    print(f"receipt sent for order {kwargs['order_id']}")


order_paid.send("checkout", order_id=42)

If you are in a Flask project, Blinker is already installed and is the natural choice. In Django, use Django's own signals.

The shorter way with Nitro Dispatch

Nitro Dispatch handles the in-app kind of signal. It does nothing with OS signals; for those, the signal module is the answer. Events are named strings, receivers run in priority order, and each one gets a data dict and hands it on:

from nitro_dispatch import PluginManager

manager = PluginManager()


def send_receipt(data):
    data["receipt_sent"] = True
    return data


def audit(data):
    print(f"order event for {data['order_id']}")
    return data


manager.register_hook("order.paid", send_receipt, priority=100)
manager.register_hook("order.*", audit, priority=10)

manager.trigger("order.paid", {"order_id": 42})
# order event for 42
# {'order_id': 42, 'receipt_sent': True}

The differences from Blinker are the ones worth choosing on. Receivers can change the data as it passes through, a wildcard such as order.* listens to a whole family of events, and a receiver that raises is logged and skipped so the rest still run. There is no sender argument: put anything a receiver needs in the dict.

For two or three events in one module, the fifteen-line Signal class is plenty.

Common questions

Why does my SIGTERM handler never run? Usually because the signal went to a different process. In Docker, a shell-form CMD makes the shell PID 1, and it does not pass SIGTERM on to Python. Use the exec form: CMD ["python", "app.py"].

Can I use signals with asyncio? Yes. Use loop.add_signal_handler(signal.SIGTERM, callback) instead of signal.signal, so the callback runs inside the event loop like any other. It is available on Unix only.

Are in-app signals asynchronous? No, not by default. In the class above, in Blinker and in Django, send calls each receiver in turn and returns when they are all done. A slow receiver slows the sender.

This page uses Nitro Dispatch.

Add plugins to any Python app. Async-ready hooks with priorities and error isolation built in.

$ pip install nitro-dispatch