In the process of development, you may often encounter a requirement that requires the output of Python's exception information to a log file.
Online methods are not very practical, the following is a practical, from the Python 2.7 source code to buckle out.
The nonsense does not say directly on the code, the code is not many, the annotation is more than just.
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 ' the ' the ' through ' e Stack in this example# see hg.python.org/cpython/file/8dffb76faacc/lib/traceback.py#l280# (Imagine if the 1/0, below, we Re replaced by a call-to-test () which did 1/0.) Try:1/0except: # 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_ is 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 does this very thing, but note this creates a temp scope within the function. "' traceback_details = {' filename ': exc_traceback.tb_frame.f_code.co_filename, ' Lineno ': exc_t RaceBack.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/objects 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] # # Modified here can be traceback anywhere, or stored in a file print traceback_template% traceback_details