python 中的 sys.excepthook 行为

and*_*tti 5 python exception

我发现 sys.excepthook 的工作原理非常令人困惑。鉴于以下情况,我找不到一种方法可以继续下去,以防异常被钩子捕获。简而言之,我从未到达打印声明,但我确信理论上这是可能继续的。返回 True 或 False 也没有帮助吗?

import sys
from shutil import copy
from subprocess import Popen


def my_except_hook(etype, value, tb):
    print("got an exception of type", etype)


if __name__ == '__main__':
    sys.excepthook = my_except_hook
    copy('sdflsdk')
    print("here")
    Popen('sdflkjdklsdj')
Run Code Online (Sandbox Code Playgroud)

那么输出是:

('got an exception of type', <type 'exceptions.TypeError'>)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ina 4

sys.excepthook 实际上并不是要被强制转换为 VB 风格的“On Error Resume Next”。可能有一种方法可以做到这一点,但您确实应该包装自己的代码来执行此操作。system.excepthook 是为诸如 python 交互式解释器之类的东西而设计的,以便它们打印异常并将您返回到交互式 shell。要执行您寻求的恢复行为,您应该考虑执行以下操作:

import sys
from shutil import copy
from subprocess import Popen

if __name__ == '__main__':
    try:
        copy('sdflsdk')
    except:
        pass
    print("here")
    try:
        Popen('sdflkjdklsdj')
    except:
        pass
Run Code Online (Sandbox Code Playgroud)