2014-12-01 132 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>而不是一個。

相關問題