0%

python atexit and CTRL-C CTRL-Z signal handler

Guide

atexit

1
2
3
4
5
6
7
8
def exit_handler():
print("exit')

import atexit
atexit.register(exit_handler)

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

ctrl+c/ ctrl+z

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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.