python atexit and CTRL-C CTRL-Z signal handler


Guide

atexit

def exit_handler():
    print("exit')

import atexit
atexit.register(exit_handler)

if __name__ == '__main__':
    print("OK)

ctrl+c/ ctrl+z

import signal
from sys import exit

def handler(signal_received, frame):
    # Handle any cleanup here
    print('SIGINT or CTRL-C detected. Exiting gracefully')

    exit(0)

if __name__ == '__main__':
    # Tell Python to run the handler() function when SIGINT is recieved
    signal.signal(signal.SIGINT, self.ctrl_exit_handler) # ctlr + c
    signal.signal(signal.SIGTSTP, self.ctrl_exit_handler) # ctlr + z

    print('Running. Press CTRL-C to exit.')
    while True:
        # Do nothing and hog CPU forever until SIGINT received.
        pass

Reference

History

  • 2020/3/20: created.

Author: kezunlin
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source kezunlin !
评论
  TOC