[英]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.