Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python server will not terminate on Ctrl+C after a request has come in

I'm dabbling with Python and HTTP. Have created this simple server script I run with python cli.py serve. The server starts and works, but the keyboard interrupt Ctrl+C only gets trough on the next page refresh, not when I actually press Ctrl+C in the terminal.. Any fix for this? Note: works immediately when no request have come in yet.

from http.server import HTTPServer, BaseHTTPRequestHandler
import sys, signal

commands = ["serve"]

class Server(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/":
            self.path = "/index.html"
        self.send_response(200)
        self.end_headers()
        self.wfile.write(bytes("Tere, maailm!!",'utf-8'))


if len(sys.argv) > 1 and sys.argv[1] in commands:
    index = commands.index(sys.argv[1])
    if index == 0: # serve command
        print("Starting web server. Press Ctrl+C to exit!")
        httpd = HTTPServer(("localhost", 8080), Server)
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("Shutting down...")
            httpd.socket.close()
            sys.exit(0)
else:
    print("Usage: python tab.py [command], where [command] is any of", commands)
like image 377
Rando Hinn Avatar asked Oct 15 '25 04:10

Rando Hinn


1 Answers

Same problem... I discovered ThreadingHTTPServer, that works (instead of HTTPServer)

like image 92
matthiasg Avatar answered Oct 17 '25 19:10

matthiasg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!