KeyboardInterrupt Exception有时会起作用吗?

时间:2014-12-01 22:13:50

标签: exception python-3.x keyboardinterrupt

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

最后一次工作。怎么有时候才有效!?我做错了什么?

1 个答案:

答案 0 :(得分:0)

如果仔细检查堆栈跟踪,您会注意到有两个例外处理:

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

第14行(在try区块中);然后在第14行或第17行再次进行下一次(在#34;手动退出&#34;块中)。

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