1

我有这个简单的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...

它最后一次工作。为什么它有时只起作用!?我究竟做错了什么?

4

1 回答 1

0

如果您仔细检查堆栈跟踪,您会注意到正在处理两个异常:

Traceback (most recent call last):
  File "listener.py", line 14, in <module>

一个在第 14 行(在try块中);下一个在第 14 行或第 17 行(在“手动退出”块中)。

在我看来,您的键盘有硬件问题,有时会发送两个<ctrl-c>s 而不是一个。

于 2015-05-22T15:54:23.120 回答