我有以下的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