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

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


I am struggling with the same thing in my project. Something that did work for me was using signal to capture CTRL-C.

import sysimport signaldef handler(signal, frame):  print('CTRL-C pressed!')  sys.exit(0)signal.signal(signal.SIGINT, handler)signal.pause()

When this piece of code is put in the script that is running the Flask app, the CTRL-C can be captured. As of now, you have to use CTRL-C twice and then the handler is executed though. I'll investigate further and edit the answer if I find something new.

Edit 1

Okay I've done some more research and came up with some other methods, as the above is quite hack 'n slash.

In production, clean-up code such as closing databases or files is done via the @app.teardown_appcontext decorator. See this part of the tutorial.

When using the simple server, you can shut it down via exposing the werkzeug shutdown function. See this post.

Edit 2

I've tested the Werkzeug shutdown function, and it also works together with the teardown_appcontext functions. So I suggest to write your teardown functions using the decorator and writing a simple function that just does the shutdown of the werkzeug server. That way production and development code are the same.