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

后端 未结 15 2339
天命终不由人
天命终不由人 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:19

    traceback.format_exception

    If you only have the exception object, you can get the traceback as a string from any point of the code in Python 3 with:

    import traceback
    
    ''.join(traceback.format_exception(None, exc_obj, exc_obj.__traceback__))
    

    Full example:

    #!/usr/bin/env python3
    
    import traceback
    
    def f():
        g()
    
    def g():
        raise Exception('asdf')
    
    try:
        g()
    except Exception as e:
        exc = e
    
    tb_str = ''.join(traceback.format_exception(None, exc_obj, exc_obj.__traceback__))
    print(tb_str)
    

    Output:

    Traceback (most recent call last):
      File "./main.py", line 12, in 
        g()
      File "./main.py", line 9, in g
        raise Exception('asdf')
    Exception: asdf
    

    Documentation: https://docs.python.org/3.7/library/traceback.html#traceback.format_exception

    See also: Extract traceback info from an exception object

    Tested in Python 3.7.3.

提交回复
热议问题