编程语言
首页 > 编程语言> > 在python中,为什么在“try except”之前和之后进行信号处理时异常存在差异

在python中,为什么在“try except”之前和之后进行信号处理时异常存在差异

作者:互联网

我最近开始使用python.当我遇到这种行为时,我正在玩处理键盘中断

import signal,sys

def handleInt(sign,no):
    print "interrupted"

signal.signal(signal.SIGINT,handleInt)    # exception raised is IOError

try:
    sys.stdin.read(1)
except IOError:
    print "io interrupt"

但如果我将信号处理改为try-except之后

import signal,sys

def handleInt(sign,no):
    print "interrupted"

try:
    sys.stdin.read(1)
except KeyboardInterrupt:
    print "keyboard interrupt"

signal.signal(signal.SIGINT,handleInt)    # exception raised is KeyboardInterrupt

当我按ctrl c时,两种情况下的异常存在差异.那么为什么会出现这种情况?

解决方法:

Python有自己内置的SIGINT单一处理程序.这个处理程序只是引发了KeyboardInterrupt.在您的第一个代码中,您使用新处理程序替换了内置处理程序,因此您会看到此输出:

$python test_exc.py 
^Cinterrupted

请注意,没有打印io中断,因为没有引发异常.实际上将代码修改为:

import signal,sys

def handleInt(sign,no):
    print "interrupted"

signal.signal(signal.SIGINT, handleInt)    # exception raised is IOError

try:
    sys.stdin.read(1)
except IOError:
    print "io interrupt"
else:
    # else is executed only if no exception was raised
    print "done"

你得到:

$python test_exc.py 
^Cinterrupted

done

请注意,按Ctrl C不会阻止对sys.stdin.read(1)的调用,因此您仍然需要按某个键才能让程序继续运行.在信号处理程序中引发异常将引发它,就好像对sys.stdin.read(1)的调用产生它一样:

import signal,sys

def handleInt(sign,no):
    print "interrupted"
    raise OSError

signal.signal(signal.SIGINT, handleInt)    # exception raised is IOError

try:
    sys.stdin.read(1)
except IOError:
    print "io interrupt"
else:
    # else is executed only if no exception was raised
    print "done"

样品运行:

$python test_exc.py 
^Cinterrupted
Traceback (most recent call last):
  File "test_exc.py", line 10, in <module>
    sys.stdin.read(1)
  File "test_exc.py", line 5, in handleInt
    raise OSError
OSError

注意:您可以通过signal.default_int_handler访问默认信号处理程序.

标签:python,signals,try-except
来源: https://codeday.me/bug/20190520/1141964.html