traceback --- 打印或检索堆栈回溯¶
该模块提供了一个标准接口来提取、格式化和打印 Python 程序的堆栈跟踪结果。它完全模仿Python 解释器在打印堆栈跟踪结果时的行为。当您想要在程序控制下打印堆栈跟踪结果时,例如在“封装”解释器时,这是非常有用的。
这个模块使用 traceback 对象 —— 这是存储在 sys.last_traceback 中的对象类型变量,并作为 sys.exc_info() 的第三项被返回。
这个模块定义了以下函数:
traceback.print_tb(tb, limit=None, file=None)¶
Print up to limit stack trace entries from traceback object tb (starting
from the caller's frame) if limit is positive. Otherwise, print the last
abs(limit) entries. If limit is omitted or None, all entries are
printed. If file is omitted or None, the output goes to
sys.stderr; otherwise it should be an open file or file-like object to
receive the output.
在 3.5 版更改:Added negative limit support.
traceback.print_exception(etype, value, tb, limit=None, file=None, chain=True)¶
打印回溯对象 tb 到 file 的异常信息和整个堆栈回溯。这和 print_tb() 比有以下方面不同:
如果 tb 不为 None,它将打印头部 Traceback (most recent call last):
it prints the exception etype and value after the stack trace
if type(value) is SyntaxError and value has the appropriate
format, it prints the line where the syntax error occurred with a caret
indicating the approximate position of the error.
The optional limit argument has the same meaning as for print_tb().
If chain is true (the default), then chained exceptions (the
__cause__ or __context__ attributes of the exception) will be
printed as well, like the interpreter itself does when printing an unhandled
exception.
在 3.5 版更改:The etype argument is ignored and inferred from the type of value.
traceback.print_exc(limit=None, file=None, chain=True)¶
This is a shorthand for print_exception(*sys.exc_info(), limit, file,
chain).
traceback.print_last(limit=None, file=None, chain=True)¶
This is a shorthand for print_exception(sys.last_type, sys.last_value,
sys.last_traceback, limit, file, chain). In general it will work only
after an exception has reached an interactive prompt (see
sys.last_type).
traceback.print_stack(f=None, limit=None, file=None)¶
Print up to limit stack trace entries (starting from the invocation
point) if limit is positive. Otherwise, print the last abs(limit)
entries. If limit is omitted or None, all entries are printed.
The optional f argument can be used to specify an alternate stack frame
to start. The optional file argument has the same meaning as for
print_tb().
在 3.5 版更改:Added negative limit support.
traceback.extract_tb(tb, limit=None)¶
Return a StackSummary object representing a list of "pre-processed"
stack trace entries extracted from the traceback object tb. It is useful
for alternate formatting of stack traces. The optional limit argument has
the same meaning as for print_tb(). A "pre-processed" stack trace
entry is a FrameSummary object containing attributes
filename, lineno,
name, and line representing the
information that is usually printed for a stack trace. The
line is a string with leading and trailing
whitespace stripped; if the source is