2012-10-15 90 views
0

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

您忘記了雙qoute'「'的'行打印(行號」,exc_traceback.tb_lineno)' – avasal

+0

,你有一個不必要的''''print'(「在算術運算中看起來像:」,格式化線[2]「,行 – avasal

回答

1

請不要嘗試使用format_exc的輸出解析堆棧跟蹤。這只是爲了產生一個人類可讀的堆棧跟蹤。

您應該改用linecache得到出錯行:

exc_type, exc_value, exc_traceback = sys.exc_info() 
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)) 
+0

我在最後一行出現語法錯誤 –

+0

您將問題標記爲Python 2.7 ...你的意思是Python 3嗎?我已經修改了答案。 – nneonneo

+0

你是對的,它是2.7,我在編輯部分包含了我的更新代碼和錯誤信息,我得到了 –