← retour aux snippets

signal: terminaison gracieuse (SIGINT/SIGTERM)

Capter les signaux et terminer proprement votre programme.

objectif

Capter les signaux et terminer proprement votre programme.

code minimal

import signal

stopping = {"flag": False}

def handler(signum, frame):
    stopping["flag"] = True

signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGTERM, handler)

# simulation d'appel du handler (sans envoyer de vrai signal)
handler(None, None)
print(stopping["flag"])  # attendu: True

utilisation

import signal
print(hasattr(signal, "SIGINT"))

variante(s) utile(s)

import threading, time
stopping = {"flag": False}
def worker():
    while not stopping["flag"]:
        time.sleep(0.01)
    # cleanup ici
print(callable(worker))

notes

  • Évitez d’appeler des fonctions non réentrantes dans un handler.
  • Sur Windows, SIGTERM n’existe pas toujours; gérez selon l’OS.