[英]Why does the Python linecache affect the traceback module but not regular tracebacks?
考虑以下Python程序:
code = """
def test():
1/0
"""
filename = "<test>"
c = compile(code, filename, 'exec')
exec(c)
import linecache
linecache.cache[filename] = (len(code), None, code.splitlines(keepends=True), filename)
import traceback
print("Traceback from the traceback module:")
print()
try:
test()
except:
traceback.print_exc()
print()
print("Regular traceback:")
print()
test()
我正在动态定义一个引发异常并将其添加到linecache
的函数。 代码的输出是
Traceback from the traceback module:
Traceback (most recent call last):
File "test.py", line 20, in <module>
test()
File "<test>", line 3, in test
1/0
ZeroDivisionError: division by zero
Regular traceback:
Traceback (most recent call last):
File "test.py", line 28, in <module>
test()
File "<test>", line 3, in test
ZeroDivisionError: division by zero
如果我然后使用traceback
模块从该函数获取回溯,则显示该函数的代码行(第一个回溯的1/0
部分)。 但是,如果我只是让代码引发异常并从解释器获得常规回溯,它就不会显示代码。
为什么常规解释器回溯不使用linecache? 有没有办法让代码出现在常规回溯中?
默认的sys.excepthook
使用单独的C级执行回溯打印,而不是traceback
模块。 (也许就是这样,即使系统过于使用traceback.py
,它仍然有效。)C实现不会尝试使用linecache
。 您可以在_Py_DisplaySourceLine
查看用于检索源代码行的_Py_DisplaySourceLine
。
如果希望回溯使用traceback
模块的实现,可以使用traceback.print_exception
替换sys.excepthook
:
import sys
import traceback
sys.excepthook = traceback.print_exception
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.