Question

I have a python 3 script and it runs on boot. And it work with some resources I want it free on exit.

How can I manage that script is going to exit if I'm killing it with kill -6 $PID.

Or any other ideas about how to send exit command and detect it in script.

Was it helpful?

Solution

The signal module is what you are looking for.

import signal

def handler(signum, frame):
    print('Signal handler called with signal', signum)

signal.signal(signal.SIGABRT, handler)

Within the handler function you could terminate with sys.exit().

However, it is more common to use SIGINT (that's what happens when you press CTRL+C in the terminal) or SIGTERM to terminate a program. If you don't have cleanup code you don't need to write a single line of code to handle SIGINT - by default it raises a KeyboardInterrupt exception which, if not caught (that's a reason why you should never use blank except: statements), causes your program to terminate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top