Sample Code for capturing detailed exception information in Python.
During the development process, you may often encounter a need to output Python exception information to the log file.
The methods on the Internet are not practical. The following describes a practical method, which is deducted from the Python 2.7 source code.
If you don't need to talk about Code directly, there are not many codes and there are more comments.
Import sys, tracebacktraceback_template = ''' Traceback (most recent call last): File "% (filename) s", line % (lineno) s, in % (name) s % (type) s: % (message) s \ n''' # Skipping the "actual line" item # Also note: we don't walk all the way through the frame stack in this example # see References (Imagine if the 1/0, below, were replaced by a call to test () whi Ch did 1/0 .) try: 1/0 bytes T: # http://docs.python.org/2/library/sys.html#sys.exc_info exc_type, exc_value, exc_traceback = sys. exc_info () # most recent (if any) by default ''' Reason this _ can _ be bad: If an (unhandled) exception happens AFTER this, or if we do not delete the labels on (not much) older versions of Py, the reference we created can linger. traceback. format_exc/print_exc do this very Thing, BUT note this creates a temp scope within the function. '''traceback_details = {'filename': Response, 'lineno': exc_traceback.tb_lineno, 'name': exc_traceback.tb_frame.f_code.co_name, 'type': exc_type. _ name __, 'message': exc_value.message, # or see traceback. _ some_str ()} del (exc_type, exc_value, exc_traceback) # So we don't leave our local labels/obj Ects dangling # This still isn't "completely safe", though! # "Best (recommended) practice: replace all exc_type, exc_value, exc_traceback # with sys. exc_info () [0], sys. exc_info () [1], sys. exc_info () [2] # modify the traceback to any location or store it in the file with print traceback_template % traceback_details.
Let's talk about python exceptions! The following is my code! What's the difference?
It should be
Finally:
F. close ()
Indicates that f should be disabled at the end of try
Failed T: indicates that the content here is executed only when an error occurs.
But in fact, if f is not off, python will automatically shut it off when the program exits, so there is no difference in your program.
Python exception
This is a programmer's thinking problem. It is not in python. You must use try... maybe t...
You can summarize the mistakes you make. If you practice more, you will not make any mistakes ..