简体   繁体   中英

sys.excepthook behaviour in python

I find quite puzzling how the sys.excepthook works. 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. 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". 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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