考虑以下Python程序:
import React from "react"
export default class App extends React.Component{
render(){
return (
<div>
<h1>From COmponent</h1>
</div>
)
}
}
我正在动态定义一个引发异常并将其添加到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
部分)。但是,如果我只是让代码引发异常并从解释器获得常规回溯,它就不会显示代码。
为什么常规解释器回溯使用linecache?有没有办法让代码出现在常规回溯中?
答案 0 :(得分:4)
默认sys.excepthook
使用单独的C级跟踪打印实现,而不是traceback
模块。 (也许就是这样,即使系统过于沉闷而无法使用traceback.py
,它仍然有效。)C实现不会尝试使用linecache
。您可以在_Py_DisplaySourceLine
中查看用于检索源代码行的代码。
如果您希望追溯使用traceback
模块的实施,您可以将sys.excepthook
替换为traceback.print_exception
:
import sys
import traceback
sys.excepthook = traceback.print_exception