Python traceback "Go"

Source: Internet
Author: User
Tags integer division python script

1. Exception stack tracking in Python

Python, in 2.x, an exception object can be any object, and the exception object and the exception stack are separate.
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.

1 deffunc (A, b):2     returnAb3 if __name__=='__main__':4     ImportSYS5     ImportTraceback6     Try:7Func (1, 0)8     exceptException as E:9         Print "Print exc"TenTraceback.print_exc (File=sys.stdout)

Output Result:

 1  print   exc  2  traceback (most recent call last):  3  File  ./teststacktrace.py  Span style= "color: #800000;"     > ", line 7, in  <module>4  Func (1 5  File  " ./teststacktrace.py  " , line 2, in   Func  6  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.

1 deffunc (A, b):2     returnAb3 if __name__=='__main__':4     ImportSYS5     ImportTraceback6     Try:7Func (1, 0)8     exceptException as E:9         Print "print_exception ()"TenExc_type, exc_value, EXC_TB =Sys.exc_info () One         Print 'The exc type is:', Exc_type A         Print 'The exc value is:', Exc_value -         Print 'The exc TB is:', EXC_TB -Traceback.print_exception (Exc_type, Exc_value, EXC_TB)

Output Result:

1 print_exception ()2The exc type is: <type'exceptions. Zerodivisionerror'>3The EXC value is: integer Divisionormodulo by Zero4The exc TB is: <traceback object at 0x104e7d4d0>5 Traceback (most recent):6File"./teststacktrace.py", Line 7,inch<module>7Func (1, 0)8File"./teststacktrace.py", Line 2,inchfunc9     returnAbTenZerodivisionerror:integer DivisionorModulo 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:

1 deffunc (A, b):2     returnAb3 if __name__=='__main__':4     ImportSYS5     ImportTraceback6     Try:7Func (1, 0)8     except:9_, _, Exc_tb =Sys.exc_info ()Ten          forFileName, linenum, funcname, sourceinchTRACEBACK.EXTRACT_TB (EXC_TB): One             Print "%-23s:%s '%s ' in%s ()"% (filename, linenum, source, funcname)

Output Result:

1 samchimac:tracebacktest samchi$ python./2 ./teststacktrace.py    'func ( 1, 0)' in <module>()3 ./teststacktrace.py    '  Return A/b' in 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:

1 deffunc (A, b):2         returnAb3 if __name__=='__main__':4         ImportCGITB5Cgitb.enable (format='text')6         ImportSYS7         ImportTraceback8Func (1, 0)

After running, you will get detailed data:

1A problem occurredinchA Python script. Here isThe sequence of2function calls leading up to the error,inchThe order they occurred.3  4/users/samchi/documents/workspace/tracebacktest/teststacktrace.pyinch<module>()54ImportCGITB65 Cgitb.enable (format='text')76ImportSYS87ImportTraceback98 Func (1, 0)TenFunc = <function func> One   A/users/samchi/documents/workspace/tracebacktest/teststacktrace.pyinchFunc (A=1, b=0) -2returnAb -3if __name__=='__main__': the4ImportCGITB -5 Cgitb.enable (format='text') -6ImportSYS -A = 1 +b = 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:

1 deffunc (A, b):2         returnAb3 defMy_exception_handler (Exc_type, Exc_value, EXC_TB):4         Print "I caught the exception:", Exc_type5          whileEXC_TB:6                 Print "The line No:", Exc_tb.tb_lineno7                 Print "The frame locals:", Exc_tb.tb_frame.f_locals8EXC_TB =Exc_tb.tb_next9  Ten if __name__=='__main__': One         ImportSYS ASys.excepthook =My_exception_handler -         ImportTraceback -Func (1, 0)

Output Result:

1I caught the exception: <type'exceptions. Zerodivisionerror'>2The line no:143The frame locals: {'My_exception_handler': <function My_exception_handler at 0x100e04aa0>'__builtins__': <module'__builtin__'(built-inch);'__file__':'./teststacktrace.py','Traceback': <module'Traceback'  from '/system/library/frameworks/python.framework/versions/2.7/lib/python2.7/traceback.pyc','__package__': None,'SYS': <module'SYS'(built-inch);'func': <function func at 0x100e04320>'__name__':'__main__','__doc__': None}4The line No:25The frame locals: {'a': 1,'b': 0}
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:

1 Logging.exception (ex) 2 # named output stack traces, Logging.exception's interior is also wrapped in a layer of this practice 3 # more severe error levels

Transferred from: http://my.oschina.net/chihz/blog/180573

Python traceback "Go"

Related Article

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.