Why does the Python linecache affect the traceback module but not regular tracebacks?
考虑下面的python程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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() |
我动态地定义了一个引发异常并将其添加到
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 |
然后,如果我使用
为什么常规的解释器回溯不使用linecache?有没有办法让代码出现在常规的回溯中?
默认的
如果希望回溯使用
1 2 3 | import sys import traceback sys.excepthook = traceback.print_exception |