Menu Close

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:

  • SIGINT: This signal is used to interrupts a process immediately. The default action of this signal is to terminate a process gracefully. This signal is generated when a user presses ctrl+c.
  • SIGTERM: This signal terminates a process immediately. This is also used for graceful termination of a process. The only difference is that, It is generated by shell command kill by default.

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):
        print("running App: ")

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

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

    while not app.shutdown:




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:

Posted in Python

Leave a Reply

Your email address will not be published. Required fields are marked *