1

I am building a Flask app and was wondering how can I tell it to do a function when the user clicks "Ctrl + C or X" basically when they end the application. For this example, let's say I just want it to open a file and write "done" to it. Is this possible?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Nathan Belete
  • 111
  • 4
  • 11
  • 2
    Have you read e.g. https://stackoverflow.com/questions/3850261/doing-something-before-program-exit? – jonrsharpe Feb 15 '20 at 23:56
  • 1
    Does this answer your question? [Doing something before program exit](https://stackoverflow.com/questions/3850261/doing-something-before-program-exit) – Brian61354270 Feb 16 '20 at 00:03

2 Answers2

0

The way the program is terminated is through signals sent by your system. Two examples of signals are SIGKILL which corresponds to kill -9 and SIGINT which corresponds to pressing ctrl + c.

You have a built-in library in Python called signals though which you could play around with signals in Unix/Linux.

Simply import the library using import signals and then write a simple callback function that runs whenever the registered signal is received.

Example of signal handler function:

def receiveSignal(signalNumber, frame):
print('Received:', signalNumber)
return

Example of registering signals

signal.signal(signal. SIGKILL, receiveSignal)
signal.signal(signal.SIGINT, receiveSignal)

Now, whenever your program received the registered signals, the receiveSignal function is called and you could handle the task of writing to the file and then exiting over there.

The example above is taken from StackAbuse and you could find the complete example here

  • This code will not pass as you are not allowed to handle `signal.SIGKILL` or `signal.SIGSTOP`. SIGTERM or SIGINT is ok. – runzhi xiao Dec 02 '22 at 06:37
-2

Use atexit to handle this, from: https://stackoverflow.com/a/30739397/5782985, I have test on my code, it worked.

import atexit

#defining function to run on shutdown
def close_running_threads():
    for thread in the_threads:
        thread.join()
    print "Threads complete, ready to finish"

#Register the function to be called on exit
atexit.register(close_running_threads)

#start your process
app.run()
Galley
  • 493
  • 6
  • 9
  • From the [atexit documentation](https://docs.python.org/3/library/atexit.html): "The functions registered via this module are not called when the program is killed by a signal not handled by Python, when a Python fatal internal error is detected, or when `os._exit()` is called." – J.T Jun 02 '22 at 14:57
  • atexit is not called when you use Ctrl+C – runzhi xiao Dec 02 '22 at 06:17
  • To expand on @J.T's point, this won't be called when your program receives `SIGTERM` unless your program also handles `SIGTERM` in a signal handler - in which case you might just as well do your cleanup in the signal handler. – Tom Jul 12 '23 at 16:06