python exception message capturing

前端 未结 11 1694
醉梦人生
醉梦人生 2020-12-12 09:06
import ftplib
import urllib2
import os
import logging
logger = logging.getLogger(\'ftpuploader\')
hdlr = logging.FileHandler(\'ftplog.log\')
formatter = logging.Form         


        
11条回答
  •  死守一世寂寞
    2020-12-12 09:41

    If you want the error class, error message, and stack trace, use sys.exc_info().

    Minimal working code with some formatting:

    import sys
    import traceback
    
    try:
        ans = 1/0
    except BaseException as ex:
        # Get current system exception
        ex_type, ex_value, ex_traceback = sys.exc_info()
    
        # Extract unformatter stack traces as tuples
        trace_back = traceback.extract_tb(ex_traceback)
    
        # Format stacktrace
        stack_trace = list()
    
        for trace in trace_back:
            stack_trace.append("File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]))
    
        print("Exception type : %s " % ex_type.__name__)
        print("Exception message : %s" %ex_value)
        print("Stack trace : %s" %stack_trace)
    

    Which gives the following output:

    Exception type : ZeroDivisionError
    Exception message : division by zero
    Stack trace : ['File : .\\test.py , Line : 5, Func.Name : , Message : ans = 1/0']
    

    The function sys.exc_info() gives you details about the most recent exception. It returns a tuple of (type, value, traceback).

    traceback is an instance of traceback object. You can format the trace with the methods provided. More can be found in the traceback documentation .

提交回复
热议问题