我有以下的Python程序:Python的堆栈跟踪模块回溯路线错误
import traceback
import sys
try:
3/0
except OverflowError as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
formatted_lines = traceback.format_exc().splitlines()
print(" It looks like in the arithmetic operation :" , formatted_lines[2], ") #gets the offending line
print (at line number " , exc_traceback.tb_lineno) #gets the line number
except ZeroDivisionError as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
formatted_lines = traceback.format_exc().splitlines()
print(" It looks like in the arithmetic operation :" , formatted_lines[2], ") #gets the offending line
print (at line number " , exc_traceback.tb_lineno) #gets t
对于简单的程序如上堆栈跟踪返回正确的行数,但对于更复杂的方法,如下面的Python会引发更多的踪迹(最新呼叫是最后一次),是否有办法找出堆栈跟踪的索引:formatted_lines[2]
以获得最新的呼叫。
try:
def prize():
print("hello")
def main():
prize()
Catch:
.....
任何帮助,将不胜感激。
也试过这样:
import traceback
import sys
import linecache
try:
2/0
except ZeroDivisionError as e:
filename = exc_traceback.tb_frame.f_code.co_filename
lineno = exc_traceback.tb_lineno
line = linecache.getline(filename, lineno)
print "exception occurred at %s:%d: %s" % (filename, lineno, line)
我在最后一行 “无效语法”
得到一个错误,当我尝试:
print (filename, lineno, line)
我得到一个错误:
Traceback (most recent call last):
File "C:\Users\Anu\Desktop\test.py", line 39, in <module>
filename = exc_traceback.tb_frame.f_code.co_filename
NameError: name 'exc_traceback' is not defined
您忘记了双qoute'“'的'行打印(行号”,exc_traceback.tb_lineno)' – avasal
,你有一个不必要的''''print'(“在算术运算中看起来像:”,格式化线[2]“,行 – avasal