如何从 socket.timeout 异常处理程序中捕获 KeyboardInterrupt?
How to catch KeyboardInterrupt from within socket.timeout exception handler?
我正在尝试开发一个具有非阻塞接受(使用 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
问题不是套接字超时。问题是您期望抛出异常的地方。将代码更改为:
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()
我正在尝试开发一个具有非阻塞接受(使用 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
问题不是套接字超时。问题是您期望抛出异常的地方。将代码更改为:
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()