Python Detect Ubuntu Shutdown Signal

October 28, 2020
import signal
import time

is_shutdown = False

def stop(signum, frame):
    global is_shutdown
    is_shutdown = True
    print('SIGTERM')

signal.signal(signal.SIGTERM, stop)

print('START')

while not is_shutdown:
    print('.', end='', flush=True)
    time.sleep(1)

print('END')
  • SIGINT: Interrupt from keyboard (CTRL + C).
  • SIGTERM: Termination signal.
  • SIGHUP: Hangup detected on controlling terminal or death of controlling process.
  • SIGKILL: Kill signal. It cannot be caught, blocked, or ignored.

NOTE: For systemd stop, you will receive SIGTERM followed by SIGHUP.

Reference:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.