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...
它最後一次工作。如何纔能有效地工作!?我究竟做錯了什麼?
我無法在3.1或3.4上進行復制。 – 2014-12-02 05:31:45