28.10.traceback — 打印或检索堆栈回溯¶
该模块提供了一个标准接口来提取、格式化和打印 Python 程序的堆栈跟踪结果。它完全模仿Python 解释器在打印堆栈跟踪结果时的行为。当您想要在程序控制下打印堆栈跟踪结果时,例如在“封装”解释器时,这是非常有用的。
The module uses traceback objects — this is the object type that is stored in
the variables sys.exc_traceback (deprecated) and
sys.last_traceback and returned as the third item from
sys.exc_info().
这个模块定义了以下函数:
traceback.print_tb(tb[, limit[, file]])¶
Print up to limit stack trace entries from the traceback object tb. 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.
traceback.print_exception(etype, value, tb[, limit[, file]])¶
Print exception information and up to limit stack trace entries from the
traceback tb to file. This differs from print_tb() in the following
ways: (1) if tb is not None, it prints a header Traceback (most
recent call last):; (2) it prints the exception etype and value after
the stack trace; (3) if etype 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.
traceback.print_exc([limit[, file]])¶
This is a shorthand for print_exception(sys.exc_type, sys.exc_value,
sys.exc_traceback, limit, file). (In fact, it uses sys.exc_info() to
retrieve the same information in a thread-safe way instead of using the
deprecated variables.)
traceback.format_exc([limit])¶
This is like print_exc(limit) but returns a string instead of printing to
a file.
2.4 新版功能.
traceback.print_last([limit[, file]])¶
This is a shorthand for print_exception(sys.last_type, sys.last_value,
sys.last_traceback, limit, file). In general it will work only after
an exception has reached an interactive prompt (see sys.last_type).
traceback.print_stack([f[, limit[, file]]])¶