Python : trackback

Internal types

  • Code objects

Code objects represent byte-compiled executable Python code, or bytecode. The difference between a code object and a function object is that the function object contains an explicit reference to the function’s globals (the module in which it was defined), while a code object contains no context; also the default argument values are stored in the function object, not in the code object (because they represent values calculated at run-time). Unlike function objects, code objects are immutable and contain no references (directly or indirectly) to mutable objects.

  • Special read-only attributes: co_name gives the function name; co_argcount is the number of positional arguments (including arguments with default values); co_nlocals is the number of local variables used by the function (including arguments); co_varnames
    is a tuple containing the names of the local variables (starting with the argument names); co_cellvars is a tuple containing the names of local variables that are referenced by nested functions; co_freevars is a tuple containing the names of free variables; co_code is a string representing the sequence of bytecode instructions; co_consts is a tuple containing the literals used by the bytecode; co_names is a tuple containing the names used by the bytecode; co_filename is the filename from which the code was compiled; co_firstlineno is the first line number of the function; co_lnotab is a string encoding the mapping from bytecode offsets to line numbers (for details see the source code of the interpreter); co_stacksize is the required stack size (including local variables); co_flags is an integer encoding a number of flags for the interpreter.
  • frame object

Frame objects represent execution frames. They may occur in traceback objects .

  • Special read-only attributes: f_back is to the previous stack frame (towards the caller), or None if this is the bottom stack frame; f_code is the code object being executed in this frame; f_locals is the dictionary used to look up local variables; f_globals is used for global variables; f_builtins is used for built-in (intrinsic) names; f_lasti gives the precise instruction (this is an index into the bytecode string of the code object).
  • Special writable attributes: f_trace, if not None, is a function called at the start of each source code line (this is used by the debugger); f_lineno is the current line number of the frame — writing to this from within a trace function jumps to the given line (only for the bottom-most frame). A debugger can implement a Jump command (aka Set Next Statement) by writing to f_lineno.
  • trackback object

Traceback objects represent a stack trace of an exception. A traceback object is created when an exception occurs. When the search for an exception handler unwinds the execution stack, at each unwound level a traceback object is inserted in front of the current traceback. When an exception handler is entered, the stack trace is made available to the program. It is accessible as the third item of the tuple returned by sys.exc_info(). When the program contains no suitable handler, the stack trace is written (nicely formatted) to the standard error stream; if the interpreter is interactive, it is also made available to the user as sys.last_traceback.

  • Special read-only attributes: tb_next is the next level in the stack trace (towards the frame where the exception occurred), or None
    if there is no next level; tb_frame points to the execution frame of the current level; tb_lineno gives the line number where the exception occurred; tb_lasti indicates the precise instruction. The line number and last instruction in the traceback may differ from the line number of its frame object if the exception occurred in a try statement with no matching except clause or with a finally clause.

traceback module

  • traceback.print_exception(etype, value, tb, limit=None, file=None, chain=True)
import sys
import traceback

def func(a, b):
        return a/b

if __name__ == '__main__':
        try:
                func(1, 0)
        except Exception as exc:
                print('print exception: ')
                exc_type, exc_value, exc_tb = sys.exc_info()
                print('the exc type is: ', exc_type)
                print('the exc value is: ', exc_value)
                print('the exc tb is: ', exc_tb)
                traceback.print_exception(exc_type, exc_value, exc_tb)

its output:

print exception: 
('the exc type is: ', <type 'exceptions.ZeroDivisionError'>)
('the exc value is: ', ZeroDivisionError('integer division or modulo by zero',))
('the exc tb is: ', <traceback object at 0x7fe4eb246c20>)
Traceback (most recent call last):
  File "test.py", line 9, in <module>
    func(1, 0)
  File "test.py", line 5, in func
    return a/b
ZeroDivisionError: integer division or modulo by zero
  • traceback.extract_tb(tb, limit=None)

Return a list of “pre-processed” stack trace entries extracted from the traceback object tb. It is useful for alternate formatting of stack traces. A “pre-processed” stack trace entry is a 4-tuple (filename, line number, function name, text) representing the information that is usually printed for a stack trace. The text is a string with leading and trailing whitespace stripped; if the source is not available it is None.

import sys
import traceback

def func(a, b):
        return a/b

if __name__ == '__main__':
        try:
                func(1, 0)
        except Exception as exc:
                _, _, exc_tb = sys.exc_info()
                for filename, linenum, funcname, source in traceback.extract_tb(exc_tb):
                        print('{0}\t:{1} "{2}" in {3}'.format(filename, linenum, source, funcname))

its output

test.py :9 "func(1, 0)" in <module>
test.py :5 "return a/b" in func
  • sys.excepthook(type, value, traceback)

This function prints out a given traceback and exception to sys.stderr.

  • When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook.
import sys
import traceback

def func(a, b):
        return a/b

def my_exception_handle(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_next

if __name__ == '__main__':
        sys.excepthook = my_exception_handle
        func(1, 0)

its output

i caught the exception:  <class 'ZeroDivisionError'>
the line no.:  16
the frame locals:  {'func': <function func at 0x7f5e351cebf8>, '__spec__': None, 'traceback': <module 'traceback' from '/usr/lib/python3.4/traceback.py'>, '__file__': 'test.py', 'sys': <module 'sys' (built-in)>, '__cached__': None, '__doc__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__package__': None, '__loader__': <_frozen_importlib.SourceFileLoader object at 0x7f5e350de8d0>, 'my_exception_handle': <function my_exception_handle at 0x7f5e33812a60>}
the line no.:  5
the frame locals:  {'a': 1, 'b': 0}
    原文作者:庞贝船长
    原文地址: https://www.jianshu.com/p/b47aeac908bd
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞