我正在尝试开发一个具有非阻塞接受的简单套接字服务器(使用settimeout),但我希望能够使用Ctrl-C(KeyboardInterrupt)来停止它。
我的代码是:
import socket
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.settimeout(1)
s.bind((host, port))
s.listen(1)
print('Server started')
while True:
try:
conn, addr = s.accept()
except socket.timeout:
pass
except Exception as exc:
print(str(exc))
print('Server closing')
s.close()
break
except KeyboardInterrupt:
print('Server closing')
s.close()
break
else:
print('Connection from', addr)
但是KeyboardInterrupt永远不会被捕获,因为它发生在socket.timeout异常处理程序中。 这是按Ctrl-C
时的输出c:\Users\JMatos\MEOCloud\Python>python file_server.py
Server started
Traceback (most recent call last):
File "file_server.py", line 40, in <module>
conn, addr = s.accept()
File "C:\Python35-32\lib\socket.py", line 195, in accept
fd, addr = self._accept()
socket.timeout: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "file_server.py", line 40, in <module>
conn, addr = s.accept()
KeyboardInterrupt
有没有办法在socket.timeout异常处理程序中捕获KeyboardInterrupt异常?
我的环境是Windows 7P + SP1 x64,Python 3.5.2 32b。
提前致谢,
JM
答案 0 :(得分:1)
问题不在于套接字超时。问题是你期望抛出异常的地方。将代码更改为:
try:
while True:
try:
conn, addr = s.accept()
except socket.timeout:
pass
except Exception as exc:
print(str(exc))
print('Server closing')
s.close()
break
else:
print('Connection from', addr)
except KeyboardInterrupt:
print('Server closing')
s.close()