2012-10-15 58 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,我在编辑部分包含了我的更新代码和错误信息,我得到了 –