SocketServer ThreadingMix For Thread_Server purposes

In the asynchronous (streaming) SocketServer example, http://docs.python.org/2/library/socketserver.html , a server thread (called server_thread) is launched to start new threads for each request. Due to some issues related to KeyboardInterrupts, I started looking for similar code and found that there is no obvious difference when NOT using the server thread, but ctrl-c really works.

Despite the fact that my code works, I would love to know

1) Why is it not a simple attempt to try KeyboardInterrupt when using server_thread?

2) What is the use of server_thread from the example - unlike my simpler example?

From the SocketServer python example, trying to intercept a keyboard in an attempt does not work:

if __name__ == "__main__":
    server = ThreadedTCPServer(serverAddr, SomeCode)
<snip>
    # Start a thread with the server -- that thread will then start one
    # more thread for each request
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.start()

: ctrl-c .

if __name__ == "__main__":
    server = ThreadedTCPServer(serverAddr, SomeCode)
    try:
        server.serve_forever()
        print "ctrl-c to exit"
    except KeyboardInterrupt:
        print  "interrupt received, exiting"
        server.shutdown() 
+4
2

1) . CTRL + C, . ( ), . . Python , non-daemon ( ). , , :

server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()

( - server_thread.start(), - Python , ). , . , - :

import signal

if __name__ == "__main__":
    server = ThreadedTCPServer(serverAddr, SomeCode)

    # some code
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.start()
    # some code

    try:
        signal.pause()  # wait for a signal, perhaps in a loop?
    except:
        server.shutdown()  # graceful quit

2) . , , ? , .

, : . , , , .

+3

, . deamon (deamon = False). , , server_forever(). , , , -deamon .

  • , , , , , KeyboardInterrupt , .
  • , . GUI .
+1

Source: https://habr.com/ru/post/1530192/


All Articles