Exception 键盘中断异常有时有效吗?
我有一个简单的python脚本:Exception 键盘中断异常有时有效吗?,exception,python-3.x,keyboardinterrupt,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
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()
当我使用Python3.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...
$sudo python3 listener.py
正在启动侦听器。。。
^CTraceback(最近一次通话最后一次):
文件“listener.py”,第14行,在
buff=s.recvfrom(65535)
键盘中断
在处理上述异常期间,发生了另一个异常:
回溯(最近一次呼叫最后一次):
文件“listener.py”,第17行,在
s、 关闭()
文件“/usr/lib/python3.2/socket.py”,第194行,关闭
def关闭(自我):
键盘中断
$sudo python3 listener.py
正在启动侦听器。。。
^CTraceback(最近一次通话最后一次):
文件“listener.py”,第14行,在
buff=s.recvfrom(65535)
键盘中断
在处理上述异常期间,发生了另一个异常:
回溯(最近一次呼叫最后一次):
文件“listener.py”,第14行,在
buff=s.recvfrom(65535)
键盘中断
$sudo python3 listener.py
正在启动侦听器。。。
^C
手动退出。。。
上次成功了。为什么它只是偶尔起作用!?我做错了什么?如果仔细检查堆栈跟踪,您会注意到有两个异常正在处理:
Traceback (most recent call last):
File "listener.py", line 14, in <module>
回溯(最近一次呼叫最后一次):
文件“listener.py”,第14行,在
第14行有一个(在try
块中);下一个在第14行或第17行(在“手动退出”块中)
在我看来,您的键盘有硬件问题,有时它会发送两个
而不是一个。我无法在3.1或3.4上复制。