SocketServer and Ctrl-C on Windows

eryk sun eryksun at gmail.com
Mon Apr 3 09:58:31 EDT 2017


On Mon, Apr 3, 2017 at 1:20 PM, Paul  Moore <p.f.moore at gmail.com> wrote:
> On Monday, 3 April 2017 14:00:18 UTC+1, eryk sun  wrote:
>> It should service the request and return to the serve_forever() loop.
>> Do you see a line logged for each request, like "[IP] - - [date] "GET
>> ..."?
>
> Yes, I see that and the page is served.
>
>>py .\example.py
> Serving HTTP on port 8000...
> 127.0.0.1 - - [03/Apr/2017 13:25:34] "GET / HTTP/1.1" 200 5470
> 127.0.0.1 - - [03/Apr/2017 13:25:34] "GET /favicon.ico HTTP/1.1" 200 5438
>
> But if I press Ctrl-C at this point, nothing happens. Even if I press Ctrl-C multiple times.

Try adding a low-level console control handler that shuts down the
server. For example:

    import sys
    import ctypes
    from wsgiref.simple_server import make_server, demo_app

    kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
    CTRL_C_EVENT = 0

    with make_server('', 8000, demo_app) as httpd:
        print("Serving HTTP on port 8000...")

        @ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_uint)
        def ctrl_handler(dwCtrlType):
            if dwCtrlType == CTRL_C_EVENT:
                print("Ctrl+C shutdown", file=sys.stderr)
                httpd.shutdown()
            return False

        if not kernel32.SetConsoleCtrlHandler(ctrl_handler, True):
            raise ctypes.WinError(ctypes.get_last_error())

        # Respond to requests until process is killed
        httpd.serve_forever()



More information about the Python-list mailing list