在異步(線程)SocketServer的示例中,啓動了一個服務器線程(稱爲server_thread),以便爲每個請求啓動新線程。由於捕捉KeyboardInterrupts的一些問題,我開始尋找類似的代碼,並發現沒有明顯的區別,當不使用服務器線程,但ctrl-c實際上工作。SocketServer ThreadingMixIn目的server_thread
即使我的代碼中使用server_thread工作時,我非常想知道
1)爲什麼沒有一個簡單的「嘗試」趕上一個KeyboardInterrupt工作?
2)來自示例的server_thread服務有什麼好處 - 與我的更簡單的示例相反?
從Python的SocketServer例如,在嘗試捕獲一個KeyboardInterrupt不起作用:
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()
您可以在'serve_forever()'中打斷ThreadedTCPServer。它沒有什麼重要的。重要的任務可能在您可能要等待的處理程序線程中。 – User