我开发了一个小型python守护程序,它使用基本套接字通信与其他程序通信。我希望程序在KeyboardInterrupt上正确关闭(关闭连接等),使用Python 2可以正常工作但使用Python 3失败。
程序使用单独的线程来处理传入的连接:
self.s = socket.socket()
self.s.bind((host, port))
self.s.listen(5)
while self.running:
c, address = self.s.accept()
# Launch new thread to handle the connection
发生以下情况:
^CException in thread Thread-1:
Traceback (most recent call last):
File "/usr/local/lib/python3.3/threading.py", line 901, in _bootstrap_inner
self.run()
File "main.py", line 80, in run
c, address = self.s.accept()
File "/usr/local/lib/python3.3/socket.py", line 135, in accept
fd, addr = self._accept()
InterruptedError: [Errno 4] Interrupted system call
在Python 2中,我可以使用以下方法捕获键盘中断:
except KeyboardInterrupt:
并处理关闭,但在Python 3中使用阻塞套接字似乎有些复杂,从不生成KeyboardInterrupt。如何捕获键盘中断和/或消除中断错误?