← retour aux snippets

signal: arrêt propre avec Event

Intercepter SIGINT/SIGTERM et arrêter une boucle proprement.

objectif

Intercepter SIGINT/SIGTERM et arrêter une boucle proprement.

code minimal

import signal, threading, time

stop = threading.Event()
def handler(signum, frame):  # type: ignore[unused-arg]
    stop.set()

# En environnement contrôlé, on appelle le handler directement
handler(signal.SIGINT, None)
print(stop.is_set())  # attendu: True

utilisation

import signal, threading, time
stop = threading.Event()
signal.signal(signal.SIGINT, lambda s, f: stop.set())
for _ in range(2):
    if stop.is_set(): break
print(isinstance(stop.is_set(), bool))

variante(s) utile(s)

import threading
e = threading.Event(); e.set()
print(e.is_set())

notes

  • Dans un script réel, reliez SIGINT/SIGTERM au flag Event.
  • Évitez les opérations non réentrantes dans un handler de signal.