私はこの単純な 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...
前回はうまくいきました。どうしてたまにしか効かないの!? 私は何を間違っていますか?