为什么 Python linecache 影响回溯模块而不影响常规回溯?

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 部分)。但如果我只是让代码引发异常并从解释器获取常规回溯,它不会显示代码。

为什么常规解释器回溯不使用行缓存?有没有办法让代码出现在常规回溯中?

默认sys.excepthook uses a separate, C-level implementation of traceback printing, not the traceback module. (Perhaps this is so it still works even if the system is too borked to use traceback.py.) The C implementation doesn't try to use linecache. You can see the code it uses to retrieve source lines in _Py_DisplaySourceLine.

如果您希望回溯使用 traceback 模块的实现,您可以将 sys.excepthook 替换为 traceback.print_exception:

import sys
import traceback
sys.excepthook = traceback.print_exception