我有这个简单的python脚本:
import socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
except socket.error as msg:
print("Could not open socket connection!")
print(msg)
sys.exit(1)
try:
s.bind(("", 0))
print("Starting the listener...")
while True:
buff = s.recvfrom(65535)
print(buff[1][0])
except KeyboardInterrupt:
s.close()
print("\nManually quitting...")
sys.exit(3)
except socket.error as msg:
s.close()
print("Socket connection failed!")
print(msg)
sys.exit(2)
except:
print("Something went wrong! Quitting...")
sys.exit(4)
s.close()
当我使用 Python 3.2.3 运行脚本时,不会一直捕获 Ctrl-C 键盘异常,这意味着有时会起作用。实际上,当尝试在任意时刻从程序中按 Ctrl-C 时,错误消息是不同的。这是脚本连续运行 3 次时控制台上的输出:
$ sudo python3 listener.py
Starting the listener...
^CTraceback (most recent call last):
File "listener.py", line 14, in <module>
buff = s.recvfrom(65535)
KeyboardInterrupt
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "listener.py", line 17, in <module>
s.close()
File "/usr/lib/python3.2/socket.py", line 194, in close
def close(self):
KeyboardInterrupt
$ sudo python3 listener.py
Starting the listener...
^CTraceback (most recent call last):
File "listener.py", line 14, in <module>
buff = s.recvfrom(65535)
KeyboardInterrupt
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "listener.py", line 14, in <module>
buff = s.recvfrom(65535)
KeyboardInterrupt
$ sudo python3 listener.py
Starting the listener...
^C
Manually quitting...
它最后一次工作。为什么它有时只起作用!?我究竟做错了什么?