Techieindoor

Python – How to stop python application or program gracefully ?

Here, we will see how to stop python application or program gracefully ? We will be using system signals to stop python program gracefully.

Generally, We use system signals to stop program gracefully. Why is this needed? Sometimes we need to collect log or useful information before abnormally existing the program or application. This can also be helpful in cleaning up resources before existing the program.

Now, we will look about signals to be used for gracefully terminating the program.

Here, we will be using two signals:

Program to demonstrate given above behaviour:

import signal
import sys
import time


class App(object):
    def __init__(self):
        self.shutdown = False
        # Registering the signals
        signal.signal(signal.SIGINT, self.exit_graceful)
        signal.signal(signal.SIGTERM, self.exit_graceful)

    def exit_graceful(self, signum, frame):
        print('Received:', signum, ": ", frame)
        self.shutdown = True

    def run(self):
        time.sleep(1)
        print("running App: ")

    def stop(self):
        # clean up the resources
        print("stop the app")

if __name__ == "__main__":
    app = App()

    while not app.shutdown:
        app.run()

    app.stop()
    sys.exit(0)

Output:

python sample.py

running App:
running App:
running App:
^CReceived: 2 :     ===>> Press ctrl + c
running App:
stop the app

To learn more about golang, Please refer given below link:

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Exit mobile version