简体   繁体   English

python中的sys.excepthook行为

[英]sys.excepthook behaviour in python

I find quite puzzling how the sys.excepthook works. 我发现sys.excepthook如何工作令人费解。 Given the following I don't find a way to just keep going in case an exception is catched by the hook. 鉴于以下内容,我找不到一种方法可以继续运行以防异常被钩子捕获。 In short I never reach the print statement, but I'm sure that is possible to continue in theory. 总之,我从未达到印刷声明,但我确信理论上可以继续。 Returning True or False didn't help either? 回归真或假也无济于事?

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')

The output is then: 输出是:

('got an exception of type', <type 'exceptions.TypeError'>)

No, it is not possible to continue in theory. 不,理论上不可能继续下去。 sys.excepthook is only called when the whole stack is unwound and no exception handler was found, just before the program would exit. sys.excepthook仅在整个堆栈被展开时调用,并且在程序退出之前没有找到异常处理程序。 There is nothing where it could continue, except exiting the program. 除了退出该计划外,没有什么可以继续的。 Are you sure you are not looking for try...except statement? 你确定你不是在寻找尝试......除了声明吗?

sys.excepthook is really not intended to be coerced into VB style "On Error Resume Next". sys.excepthook实际上并不打算被强制转换为VB样式“On Error Resume Next”。 There might be a way to do it but you should really be wrapping your own code to do this. 可能有办法做到这一点,但你应该真的包装自己的代码来做到这一点。 The system.excepthook is designed for things like python interactive interpreters so that they print the exception and return you to interactive shell. system.excepthook是为python交互式解释器之类的东西设计的,这样它们就可以打印异常并返回到交互式shell。 To do the resume behaviour you seek you should consider doing something like this: 要做你要求的简历行为你应该考虑做这样的事情:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM