Python Traceback Learning (GO)

Source: Internet
Author: User

1. Exception stack tracking in Python

Before doing Java, the exception object by default contains StackTrace related information, through the method of the Exception object Printstacktrace () and Getstacktrace () and other methods can be taken to the exception stack information, Can print to log assist debugging or do something else. But in Python, in 2.x, the exception object can be any object, often see a lot of code is directly raise a string out, so it is not as easy as Java to get the exception stack, because the exception object and the exception stack is separate. While most of the Python language books focus on describing how to construct the exception object in Python and the use of raise try except finally, the stacktrace that plays a key role in debugging is often largely not involved.

The module for handling exception stacks in Python is the Traceback module, which provides commonly used tool functions such as print_exception, format_exception, and other output exception stacks.

Func(A, B):return a/b' __main__ ':import sysimport tracebackTry:func (0) ase:" Print exc "Traceback.print_exc (file=sys.stdout)        

Output Result:

Last): In  <module> func (return A/b 

In fact, the TRACEBACK.PRINT_EXC () function is just a shorthand for the traceback.print_exception () function, and the data they get about the exception is obtained through the Sys.exc_info () function.

DefFunc(A, B): Return a/bif __name__ = = ' __main__ ':import sysimport tracebacktry:func (1, 0 )except Exception as E:print "print_exception ()" Exc_type, exc_value, EXC_TB = Sys.exc_info ()  Print ' The exc type is: ', exc_typeprint ' The exc value was: ', exc_valueprint ' The exc TB is: ', exc _tbtraceback.print_exception (Exc_type, Exc_value, EXC_TB)         

Output Result:

Print_exception () The EXC typeis: <type' Exceptions. Zerodivisionerror ' >the exc valueis:integer Division or modulo by Zerothe exc TB is: <traceback object at 0x104e7d4d0>traceback (most recent call last): File 7, in <module> func (1, 0) File Span class= "hljs-string" "./teststacktrace.py", line 2, in Func return a/bzerodivisionerror: integer Division or modulo by zero       

The value returned by Sys.exc_info () is a tuple, where the first element, Exc_type is the object type of the exception, Exc_value is the value of the exception, EXC_TB is a Traceback object, and the object contains data such as the number of rows and locations of the error. These exception data are then collated and exported through the Print_exception function.

The Traceback module provides a EXTRACT_TB function to explain the data contained in the Traceback object in more detail:

Func(A, B):return a/b' __main__ ':import sysimport tracebackTry:func (0)Except:_, _, EXC_TB = Sys.exc_info ()in Traceback.extract_tb (EXC_TB):"%-23s:%s '%s ' in%s ()"% (filename, linenum, source, Fu NCName)         

Output Result:

Samchimac:tracebacktest samchi$ python./teststacktrace.py./teststacktrace.py    :7 'func(in< Module> ()./teststacktrace.py:2 'func()      
2. Use CGITB to simplify exception debugging

If you usually develop like log-based debugging, then you may often do such things, after the discovery of the exception in log, because the information is not enough, then add some additional debug log to the value of the relevant variable output. After commissioning, remove these debug logs. There is no need to be so troublesome, the Python library provides the CGITB module to help do these things, it can output the exception context all relevant variables information, do not have to manually add debug log each time.

The use of CGITB simply cannot be imagined:

Func(A, B): Return a/        bimport CGITB cgitb.enable (format=import traceback func (0) /c6> 

After running, you will get detailed data:

A problem occurredIn aPython script.HereIs the sequence Offunction calls leading the error,In the order they occurred. /users/samchi/documents/workspace/tracebacktest/teststacktrace.pyIn <module> ()4Import CGITB5 cgitb.enable (format= ' text ')6Import Sys7Import Traceback8Func(1,0)Func = <function func>/users/samchi/Documents/workspace/tracebacktest/teststacktrace.py in func (a=< Span class= "Hljs-number" >1, B=0) 2  Return A/b 3 if __name__ = = ' __main__ ': 4 import cgitb 5 cgitb.enable ( format= ' text ') 6 import Sysa = 1b = Span class= "Hljs-number" >0             

Completely do not have to go to Log.debug ("a=%d"% a), personal feeling CGITB on-line environment is not suitable for use, suitable for debugging in the process of development, very convenient.

Maybe you'll ask, why is CGITB so fucking? Can you get such a detailed error message? In fact, it works as simple as its use, it just overrides the default Sys.excepthook function, Sys.excepthook is a default global exception blocker, you can try to modify it yourself:

DefFunc (A, B): return a/bdef my_exception_handler (Exc_type, Exc_value, exc _TB): print  "I caught the exception:", Exc_type while exc_tb: print " the Line no: ", exc_tb.tb_ Lineno print  "the frame locals:", Exc_tb.tb_frame.f_locals exc_ TB = Exc_tb.tb_nextif __name__ =  ' __main__ ': import sys sys.excepthook = my_exception_handler import traceback func (1, 0)         

Output Result:

I caught the exception: <type' Exceptions. Zerodivisionerror ' >the Line no:14the Frame locals: {' My_exception_handler ': <function My_exception_handler at0x100e04aa0>,' __builtins__ ': <Module' __builtin__ ' (built-in);' __file__ ':'./teststacktrace.py ',' Traceback ': <module  ' traceback ' from  '/SYSTEM/LIBRARY/FRAMEWORKS/PYTHON.FRAMEWORK/VERSIONS/2.7/LIB/PYTHON2.7/TRACEBACK.PYC ' > ,  ' sys ': < Module in), function func at 0X100E04320>  ' __name__ ':  ' __main__ ',  ' __doc__ ': None}the Line No: 2the frame locals: { ' a ': 1,  ' B ': 0}     

Do you see it? There is nothing magical, just the value of the related variable that gets from the stack frame object. There are also many magical attributes in the frame object that are not explored.

3. Use the logging module to record exceptions

When using Java, it is easy to record exceptions with log4j, As long as the exception object is passed to the Log.error method, but not in Python, if the exception object is passed directly to Log.error, then only a single row of the value of the exception object in the log.

The proper way to log the log in Python is this:

Logging. Exception (ex)logging. Error (ex, exc_info=logging. The interior of exception is also covered by this practice  Logging. Critical (ex, exc_info=1) # more severe error levels
Transfer from Http://www.tuicool.com/articles/f2uumm
What is the difference between traceback.print_exc () and Traceback.format_exc ()? Format_exc () returns a string, Print_exc () is printed directly. That is, Traceback.print_exc () is the same as the print traceback.format_exc () effect. Print_exc () can also accept the file parameter to write directly to one of the files. For example Traceback.print_exc (File=open (' tb.txt ', ' w+ ')) is written to the Tb.txt file.

Python Traceback Learning (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.