On this page
traceback —打印或检索堆栈回溯
源代码: Lib/traceback.py
该模块提供了一个标准接口,用于提取,格式化和打印 Python 程序的堆栈跟踪。它精确地模仿了 Python 解释器在打印堆栈跟踪时的行为。当您想在程序控制下打印堆栈跟踪时,例如在解释器周围的“包装器”中,这很有用。
该模块使用回溯对象-这是存储在sys.last_traceback变量中并作为第二项从sys.exc_info()返回的对象类型。
该模块定义了以下Function:
traceback.
print_tb
(* tb , limit = None , file = None *)- 如果* limit 为正,则最多打印来自 traceback 对象 tb 的 limit 堆栈跟踪条目(从调用者的框架开始)。否则,打印最后的
abs(limit)
个条目。如果Ellipsis limit 或None
,则将打印所有条目。如果Ellipsis file *或None
,则输出转到sys.stderr
;否则,它应该是一个打开的文件或类似文件的对象以接收输出。
- 如果* limit 为正,则最多打印来自 traceback 对象 tb 的 limit 堆栈跟踪条目(从调用者的框架开始)。否则,打印最后的
在版本 3.5 中更改:添加了负* limit *支持。
traceback.
print_exception
(* etype , value , tb , limit = None , file = None , chain = True *)- 从异常对象* tb 到 file *打印异常信息和堆栈跟踪条目。这与print_tb()在以下方面不同:
如果* tb *不是
None
,则打印标题Traceback (most recent call last):
它在堆栈跟踪之后输出异常* etype 和 value *
如果* type(value)是SyntaxError并且 value *具有适当的格式,则它将打印发生语法错误的行,并带有脱字号,以指示错误的大致位置。
可选的* limit 参数与print_tb()的含义相同。如果 chain *为 true(默认设置),则也将打印链式异常(异常的__cause__
或__context__
属性),就像解释器本身在打印未处理的异常时所做的一样。
在版本 3.5 中进行了更改:* etype 参数被忽略,并从 value *的类型推断出。
traceback.
print_exc
(* limit = None , file = None , chain = True *)- 这是
print_exception(*sys.exc_info(), limit, file, chain)
的简写。
- 这是
traceback.
print_last
(* limit = None , file = None , chain = True *)- 这是
print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain)
的简写。通常,它仅在异常到达交互式提示后才有效(请参见sys.last_type)。
- 这是
traceback.
print_stack
(* f = None , limit = None , file = None *)- 如果* limit 为正,则最多打印 limit 个堆栈跟踪条目(从调用点开始)。否则,打印最后的
abs(limit)
个条目。如果Ellipsis limit 或None
,则打印所有条目。可选的 f 参数可用于指定要启动的备用堆栈帧。可选的 file *参数与print_tb()的含义相同。
- 如果* limit 为正,则最多打印 limit 个堆栈跟踪条目(从调用点开始)。否则,打印最后的
在版本 3.5 中更改:添加了负* limit *支持。
traceback.
extract_tb
(* tb , limit = None *)- 返回一个StackSummary对象,该对象表示从跟踪对象* tb 中提取的“预处理”堆栈跟踪条目的列表。对于堆栈跟踪的备用格式很有用。可选的 limit *参数与print_tb()的含义相同。 “预处理”堆栈跟踪条目是FrameSummary对象,其中包含属性
filename
,lineno
,name
和line
,这些属性表示通常为堆栈跟踪打印的信息。line
是一个字符串,其中前导空格和尾随空格被去除;如果源不可用,则为None
。
- 返回一个StackSummary对象,该对象表示从跟踪对象* tb 中提取的“预处理”堆栈跟踪条目的列表。对于堆栈跟踪的备用格式很有用。可选的 limit *参数与print_tb()的含义相同。 “预处理”堆栈跟踪条目是FrameSummary对象,其中包含属性
traceback.
extract_stack
(* f = None , limit = None *)- 从当前堆栈帧中提取原始回溯。返回值的格式与extract_tb()相同。可选的* f 和 limit *参数与print_stack()的含义相同。
traceback.
format_list
(* extracted_list *)- 给定extract_tb()或extract_stack()返回的 Tuples 或FrameSummary对象的列表,返回准备打印的字符串列表。结果列表中的每个字符串都对应于参数列表中具有相同索引的项目。每个字符串以换行符结尾;对于源文本行不是
None
的那些项目,字符串也可以包含内部换行符。
- 给定extract_tb()或extract_stack()返回的 Tuples 或FrameSummary对象的列表,返回准备打印的字符串列表。结果列表中的每个字符串都对应于参数列表中具有相同索引的项目。每个字符串以换行符结尾;对于源文本行不是
traceback.
format_exception_only
(* etype , value *)- 格式化回溯的异常部分。参数是异常类型和值,例如
sys.last_type
和sys.last_value
给出的值。返回值是一个字符串列表,每个字符串都以换行符结尾。通常,列表只包含一个字符串。但是,对于SyntaxErrorexception,它包含多行(在打印时)显示有关语法错误发生位置的详细信息。指示发生哪个异常的消息是列表中总是最后一个字符串。
- 格式化回溯的异常部分。参数是异常类型和值,例如
traceback.
format_exception
(* etype , value , tb , limit = None , chain = True *)- 格式化堆栈跟踪和异常信息。这些参数与print_exception()的相应参数具有相同的含义。返回值是一个字符串列表,每个字符串都以换行符结尾,有些包含内部换行符。连接并打印这些行时,将打印与print_exception()完全相同的文本。
在版本 3.5 中进行了更改:* etype 参数被忽略,并从 value *的类型推断出。
traceback.
format_exc
(* limit = None , chain = True *)- 类似于
print_exc(limit)
,但返回字符串而不是打印到文件。
- 类似于
traceback.
format_tb
(* tb , limit = None *)format_list(extract_tb(tb, limit))
的简写。
traceback.
format_stack
(* f = None , limit = None *)format_list(extract_stack(f, limit))
的简写。
traceback.
clear_frames
(* tb *)- pass调用每个框架对象的
clear()
方法来清除回溯* tb *中所有堆栈框架的局部变量。
- pass调用每个框架对象的
3.4 版的新Function。
traceback.
walk_stack
(* f *)- 从给定的帧沿
f.f_back
跟随堆栈,产生每个帧的帧和行号。如果* f *是None
,则使用当前堆栈。该帮助程序与StackSummary.extract()一起使用。
- 从给定的帧沿
3.5 版中的新Function。
traceback.
walk_tb
(* tb *)- 在
tb_next
之后走回溯,产生每个帧的帧号和行号。该帮助程序与StackSummary.extract()一起使用。
- 在
3.5 版中的新Function。
该模块还定义了以下类:
TracebackException Objects
3.5 版中的新Function。
TracebackException对象是根据实际异常创建的,以捕获数据,以供以后以轻巧的方式打印。
- 类
traceback.
TracebackException
(* exc_type , exc_value , exc_traceback ,**,* limit = None , lookup_lines = True , capture_locals = False *)- 捕获异常以供以后渲染。 * limit , lookup_lines 和 capture_locals *与StackSummary类相同。
请注意,捕获本地人时,它们也会显示在回溯中。
__cause__
- 原始
__cause__
中的TracebackException。
- 原始
__context__
- 原始
__context__
中的TracebackException。
- 原始
__suppress_context__
- 原始异常中的
__suppress_context__
值。
- 原始异常中的
stack
- StackSummary表示回溯。
exc_type
- 原始回溯的类。
filename
- 对于语法错误-发生错误的文件名。
lineno
- 对于语法错误-发生错误的行号。
text
- 对于语法错误-发生错误的文本。
offset
- 对于语法错误-发生错误的文本的偏移量。
msg
- 对于语法错误-编译器错误消息。
类方法
from_exception
((* exc ,**,* limit = None , lookup_lines = True , capture_locals = False *)- 捕获异常以供以后渲染。 * limit , lookup_lines 和 capture_locals *与StackSummary类相同。
请注意,捕获本地人时,它们也会显示在回溯中。
format
(**, chain = True *)- 格式化异常。
如果* chain *不是True
,则__cause__
和__context__
不会被格式化。
返回值是一个字符串生成器,每个字符串都以换行符结尾,其中一些包含内部换行符。 print_exception()是此方法的包装器,它仅将行打印到文件中。
指示发生哪个异常的消息始终是输出中的最后一个字符串。
format_exception_only
( )- 格式化回溯的异常部分。
返回值是一个字符串生成器,每个字符串都以换行符结尾。
通常,生成器发出一个字符串。但是,对于SyntaxErrorexception,它发出几行(在打印时)显示有关语法错误发生位置的详细信息。
指示发生哪个异常的消息始终是输出中的最后一个字符串。
StackSummary Objects
3.5 版中的新Function。
StackSummary对象代表准备好进行格式化的调用堆栈。
- 类别
traceback.
StackSummary
-
- 类方法
extract
((* frame_gen ,**,* limit = None , lookup_lines = True , capture_locals = False *) - 从帧生成器构造StackSummary对象(例如walk_stack()或walk_tb()返回)。
- 类方法
-
如果提供了* limit ,则仅从 frame_gen 中获取这么多帧。如果 lookup_lines 为False
,则返回的FrameSummary对象将尚未读取其行,从而使创建StackSummary的成本降低(如果可能实际上没有被格式化,则可能很有价值)。如果 capture_locals *为True
,则将每个FrameSummary中的局部变量捕获为对象表示形式。
类方法
from_list
(* a_list *)- 从提供的FrameSummary对象列表或 Tuples 的旧列表中构造StackSummary对象。每个 Tuples 应为 4 个 Tuples,并以文件名,行号,名称,行作为元素。
format
( )- 返回准备好打印的字符串列表。结果列表中的每个字符串对应于堆栈中的单个帧。每个字符串以换行符结尾;对于带有源文本行的项目,字符串也可能包含内部换行符。
对于同一帧和同一行的长序列,将显示前几次重复,其后是摘要行,指出进一步重复的确切次数。
在版本 3.6 中更改:现在缩写了重复帧的长序列。
FrameSummary Objects
3.5 版中的新Function。
FrameSummary对象表示回溯中的单个帧。
-
- class *
traceback.
FrameSummary
(* filename , lineno , name , lookup_line = True , locals = None , line = None *)
- 表示正在格式化或打印的回溯或堆栈中的单个框架。它可以选择包含其中包含的本地帧的字符串化版本。如果* lookup_line *为
False
,则在FrameSummary访问line
属性之前(在将其强制转换为 Tuples 时也会发生),才查找源代码。line
可以直接提供,并且将完全避免进行行查找。 * locals *是可选的局部变量字典,如果提供,则变量表示形式将存储在摘要中以供以后显示。
- class *
Traceback Examples
这个简单的示例实现了一个基本的 read-eval-print 循环,类似于(但比标准的 Python 交互式解释器循环有用)。有关解释器循环的更完整实现,请参阅code模块。
import sys, traceback
def run_user_code(envdir):
source = input(">>> ")
try:
exec(source, envdir)
except Exception:
print("Exception in user code:")
print("-"*60)
traceback.print_exc(file=sys.stdout)
print("-"*60)
envdir = {}
while True:
run_user_code(envdir)
以下示例演示了打印和格式化异常及回溯的不同方法:
import sys, traceback
def lumberjack():
bright_side_of_death()
def bright_side_of_death():
return tuple()[0]
try:
lumberjack()
except IndexError:
exc_type, exc_value, exc_traceback = sys.exc_info()
print("*** print_tb:")
traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
print("*** print_exception:")
# exc_type below is ignored on 3.5 and later
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=2, file=sys.stdout)
print("*** print_exc:")
traceback.print_exc(limit=2, file=sys.stdout)
print("*** format_exc, first and last line:")
formatted_lines = traceback.format_exc().splitlines()
print(formatted_lines[0])
print(formatted_lines[-1])
print("*** format_exception:")
# exc_type below is ignored on 3.5 and later
print(repr(traceback.format_exception(exc_type, exc_value,
exc_traceback)))
print("*** extract_tb:")
print(repr(traceback.extract_tb(exc_traceback)))
print("*** format_tb:")
print(repr(traceback.format_tb(exc_traceback)))
print("*** tb_lineno:", exc_traceback.tb_lineno)
该示例的输出将类似于以下内容:
*** print_tb:
File "<doctest...>", line 10, in <module>
lumberjack()
*** print_exception:
Traceback (most recent call last):
File "<doctest...>", line 10, in <module>
lumberjack()
File "<doctest...>", line 4, in lumberjack
bright_side_of_death()
IndexError: tuple index out of range
*** print_exc:
Traceback (most recent call last):
File "<doctest...>", line 10, in <module>
lumberjack()
File "<doctest...>", line 4, in lumberjack
bright_side_of_death()
IndexError: tuple index out of range
*** format_exc, first and last line:
Traceback (most recent call last):
IndexError: tuple index out of range
*** format_exception:
['Traceback (most recent call last):\n',
' File "<doctest...>", line 10, in <module>\n lumberjack()\n',
' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n',
' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n',
'IndexError: tuple index out of range\n']
*** extract_tb:
[<FrameSummary file <doctest...>, line 10 in <module>>,
<FrameSummary file <doctest...>, line 4 in lumberjack>,
<FrameSummary file <doctest...>, line 7 in bright_side_of_death>]
*** format_tb:
[' File "<doctest...>", line 10, in <module>\n lumberjack()\n',
' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n',
' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n']
*** tb_lineno: 10
以下示例显示了打印和格式化堆栈的不同方法:
>>> import traceback
>>> def another_function():
... lumberstack()
...
>>> def lumberstack():
... traceback.print_stack()
... print(repr(traceback.extract_stack()))
... print(repr(traceback.format_stack()))
...
>>> another_function()
File "<doctest>", line 10, in <module>
another_function()
File "<doctest>", line 3, in another_function
lumberstack()
File "<doctest>", line 6, in lumberstack
traceback.print_stack()
[('<doctest>', 10, '<module>', 'another_function()'),
('<doctest>', 3, 'another_function', 'lumberstack()'),
('<doctest>', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')]
[' File "<doctest>", line 10, in <module>\n another_function()\n',
' File "<doctest>", line 3, in another_function\n lumberstack()\n',
' File "<doctest>", line 8, in lumberstack\n print(repr(traceback.format_stack()))\n']
最后一个示例演示了最后几个格式化Function:
>>> import traceback
>>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
... ('eggs.py', 42, 'eggs', 'return "bacon"')])
[' File "spam.py", line 3, in <module>\n spam.eggs()\n',
' File "eggs.py", line 42, in eggs\n return "bacon"\n']
>>> an_error = IndexError('tuple index out of range')
>>> traceback.format_exception_only(type(an_error), an_error)
['IndexError: tuple index out of range\n']