2014-12-01 85 views
1

我有这个简单的Python脚本:KeyboardInterrupt异常有时候工作?

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... 

它最后一次工作。如何才能有效地工作!?我究竟做错了什么?

+0

我无法在3.1或3.4上进行复制。 – 2014-12-02 05:31:45

回答

0

如果您检查堆栈跟踪细心,你会发现有例外正在处理:

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

一个上线14(在try块);和下一个再次在第14行或第17行(在“Manually quiting”块中)。

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