3 ms·
I recently wrote a little data transfer service in python that runs in ECS. When developing it locally it was easy to handle SIGINT: try write a batch, except K
by efxhoy 2y ago
I recently wrote a little data transfer service in python that runs in ECS. When developing it locally it was easy to handle SIGINT: try write a batch, except KeyboardInterrupt, if caught mark the transfer as incomplete and finally commit the change and shut down.
But there’s no exception in python to catch for a SIGTERM, which is what ECS and other service mangers send when it’s time to shut down. So I had to add a signal handler. Would have been neat if SIGTERM could be caught like SIGINT with a “native” exception.
- Spivak 2y agoI mean you can just have the signal handler throw StopRequested in your Python boilerplate and never think about it again. One common pattern is raising KeyboardInterrupt from your handler so it's all handled the same.
- mananaysiempre 2y agofrom signal import SIGTERM, raise_signal, signal import sys # for excepthook class Terminate(BaseException): pass def _excepthook(type, value, traceback): if not issubclass(type, Terminate): return _prevhook(type, value, traceback) # If a Terminate went unhandled, make sure we are killed # by SIGTERM as far as wait(2) and friends are concerned. signal(SIGTERM, _prevterm) raise_signal(SIGTERM) _prevhook, sys.excepthook = sys.excepthook, _excepthook def terminate(signo=SIGTERM, frame=None): signal(SIGTERM, _prevterm) raise Terminate _prevterm = signal(SIGTERM, terminate)