0
$\begingroup$

I'm running a local server using http.server like this:

from http.server import HTTPServer, BaseHTTPRequestHandler

class ServerHandler(BaseHTTPRequestHandler):
    def do_POST(self):
       ...

if __name__ == "__main__":
    print("Starting server at "+str(PORT)+"...")
    server = HTTPServer(('', PORT), ServerHandler)
    server.serve_forever()
    

I want to invoke a function before stopping the server using Ctrl+C in the terminal
how do I do so?

$\endgroup$

1 Answer 1

0
$\begingroup$

Found the solution

import signal

default_handler = None

def handler(num, frame):    
    # Do something that cannot throw here (important)
    print("Hello World")

    return default_handler(num, frame) 

if __name__ == "__main__":
    default_handler = signal.getsignal(signal.SIGINT)

    # Assign the new handler
    signal.signal(signal.SIGINT, handler)
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .