How to capture ctrl-c for killing a Flask python script

Viewed 8577

I have the following script which just boots up a web server serving a dynamically created website. In order to get dynamic data the script opens a file to read the data.

My concern is how can I catch CTRL-C command for killing the python script so I can close the file before script thread is killed.

I tried the following couple things but neither work:

from flask import Flask, render_template
import time

# Initialize the Flask application
app = Flask(__name__)

fileNames = {}
fileDesc = {}
for idx in range(1,4):
    fileNames["name{}".format(idx)] = "./name" + str(idx) + ".txt"
    fileDesc["name{}".format(idx)] = open(fileNames["name{}".format(idx)],'r')

try:
    @app.route('/')
    def index():
        # code for reading data from files
        return render_template('index.html', var1 = var1)

    @app.errorhandler(Exception)
    def all_exception_handler(error):
        print("Closing")
        for key, value in fileDesc:
            val.close()
        print("Files closed")


    if __name__ == '__main__':
        app.run(
            host="192.168.0.166",
            port=int("8080"),
            debug=True
        )

except KeyboardInterrupt:
    print("Closing")
    for key, value in fileDesc:
        val.close()
    print("Files closed")

Thanks in advance.

2 Answers

Use atexit to handle this, from: https://stackoverflow.com/a/30739397/5782985

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()
Related