【发布时间】:2018-11-04 01:17:08
【问题描述】:
考虑以下 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?有没有办法让代码出现在常规回溯中?
【问题讨论】: