Flask server won't stop on Ctrl+C in Windows

Viewed 11565

I created a default basic web server with Flask from Visual Studio templates. When I launch it from the command prompt it says "Press Ctrl+C to quit". When I do press Ctrl+C, nothing happens and the server keeps running.

Question: Is there a way to make Flask stop on Ctrl+C as advertised?

This is the code of server startup:

from os import environ
from myapp import app

if __name__ == '__main__':
    HOST = environ.get('SERVER_HOST', 'localhost')
    try:
        PORT = int(environ.get('SERVER_PORT', '5555'))
    except ValueError:
        PORT = 5555
    app.run(HOST, PORT)
3 Answers

To stop a Flask server running on Windows:

  1. Ctrl+c
  2. If Flask is still running, try: Ctrl+Break
  3. If Flask is still running, open a command terminal or PowerShell and run:
taskkill /f /im python.exe

You can also select a specific Python process to kill:

> tasklist /fi "imagename eq python.exe"

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
python.exe                    1080 Console                    8     72,456 K
python.exe                   15860 Console                    8     73,344 K

> taskkill /F /pid 15860
SUCCESS: The process with PID 15860 has been terminated.
  1. If the server is only run on the local computer, another option is to create an endpoint to kill the server.
from flask import request
def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

@app.route('/shutdown', methods=['POST'])
def shutdown():
    shutdown_server()
    return 'Server shutting down...'

although it's a strange problem you can kill the flask by run this command in linux command line:

sudo kill servicename

replace servicename with service PID

you can get it by run this command:

sudo ps -A | grep "python(x)" 

where x it's python version

You should use TASKKILL in a new command prompt window

Related