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

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

    python 3 solution

    stacktrace_helper.py

    from linecache import getline
    import sys
    import traceback
    
    
    def get_stack_trace():
        exc_type, exc_value, exc_tb = sys.exc_info()
        trace = traceback.format_stack()
        trace = list(filter(lambda x: ("\\lib\\" not in x and "/lib/" not in x and "stacktrace_helper.py" not in x), trace))
        ex_type = exc_type.__name__
        ex_line = exc_tb.tb_lineno
        ex_file = exc_tb.tb_frame.f_code.co_filename
        ex_message = str(exc_value)
        line_code = ""
        try:
            line_code = getline(ex_file, ex_line).strip()
        except:
            pass
    
        trace.insert(
            0, f'File "{ex_file}", line {ex_line}, line_code: {line_code} , ex: {ex_type} {ex_message}',
        )
        return trace
    
    
    def get_stack_trace_str(msg: str = ""):
        trace = list(get_stack_trace())
        trace_str = "\n".join(list(map(str, trace)))
        trace_str = msg + "\n" + trace_str
        return trace_str
    
    

提交回复
热议问题