How to catch and print the full exception traceback without halting/exiting the program?

后端 未结 15 2239
天命终不由人
天命终不由人 2020-11-22 13:46

I want to catch and log exceptions without exiting, e.g.,

try:
    do_stuff()
except Exception, err:
    print(Exception, err)
    # I want to print the entir         


        
15条回答
  •  無奈伤痛
    2020-11-22 14:11

    If you have an Error object already, and you want to print the whole thing, you need to make this slightly awkward call:

    import traceback
    traceback.print_exception(type(err), err, err.__traceback__)
    

    That's right, print_exception takes three positional arguments: The type of the exception, the actual exception object, and the exception's own internal traceback property.

    In python 3.5 or later, the type(err) is optional... but it's a positional argument, so you still have to explicitly pass None in its place.

    traceback.print_exception(None, err, err.__traceback__)
    

    I have no idea why all of this isn't just traceback.print_exception(err). Why you would ever want to print out an error, along with a traceback other than the one that belongs to that error, is beyond me.

提交回复
热议问题