How To Stop Python Server

In this blog post, we will discuss how to stop a Python server running on your local machine. This can be useful when you have finished testing your server, or if you need to stop the server for any reason. We will cover two methods to stop a Python server: stopping a server created with the http.server module and stopping a server using the Flask web framework.

Method 1: Stopping a Python server using http.server module

Let’s say you have started a Python server using the http.server module. The command you might have used to start the server is:

    python -m http.server 8080
    

Now, to stop this server, you can use the following steps:

  1. Locate the command prompt or terminal window where you started the server.
  2. Press Ctrl + C to send a keyboard interrupt to the server. This will stop the server and return the control to the command prompt or terminal.
  3. If the server does not stop after pressing Ctrl + C, you can try to forcefully kill the server process. You can find the process ID (PID) of the server using the following command (replace 8080 with your server’s port number):
    # On Linux or macOS
    lsof -i :8080

    # On Windows
    netstat -ano | findstr :8080
    

Once you have the PID, you can kill the process using the following command:

    # On Linux or macOS
    kill <pid>

    # On Windows
    taskkill /F /PID <pid>
    

Method 2: Stopping a Python server using Flask web framework

If you are using the Flask web framework to create your Python server, you can stop the server in a similar way to the http.server module. Here’s an example of starting a Flask server:

    from flask import Flask
    app = Flask(__name__)

    @app.route('/')
    def hello():
        return "Hello, World!"

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

To stop the Flask server, follow these steps:

  1. Locate the command prompt or terminal window where you started the server.
  2. Press Ctrl + C to send a keyboard interrupt to the server. This will stop the server and return the control to the command prompt or terminal.
  3. If the server does not stop after pressing Ctrl + C, you can follow the same process as described in Method 1 to find the PID and kill the server process.

Now you know how to stop a Python server, whether you’re using the http.server module or the Flask web framework. Remember to always properly stop your server to avoid any potential issues and to free up system resources.