Interview Prep/Python for DevOps/OS, filesystem, subprocess & CLIs

How do you handle signals like SIGTERM in a Python process?

AdvancedConceptOS, filesystem, subprocess & CLIs
Answer

Kubernetes and Docker send SIGTERM and then SIGKILL after the grace period. Install a handler that sets a flag, finish the current unit of work, and exit cleanly.

import signal, threading
stop = threading.Event()
def handle(signum, frame):
    log.info("received %s, shutting down", signal.Signals(signum).name)
    stop.set()
signal.signal(signal.SIGTERM, handle)
signal.signal(signal.SIGINT, handle)

while not stop.is_set():
    process_one_batch()
    stop.wait(5)

Handlers run only in the main thread. If Python is not PID 1 (a shell wrapper is), it may never see the signal, so use exec-form ENTRYPOINT.

All Python for DevOps questions Roadmap: Python for automation

More on OS, filesystem, subprocess & CLIs