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.
More on OS, filesystem, subprocess & CLIs
`os.path` vs `pathlib`: which do you use and why?BeginnerHow do you read environment variables safely?BeginnerHow do you walk a directory tree and find files?BeginnerWhat does `shutil` give you that `os` does not?BeginnerHow do you run an external command correctly with `subprocess`?BeginnerWhy is `shell=True` dangerous, and when is it acceptable?Intermediate