Python堆栈跟踪模块回溯线路错误

时间:2012-10-15 05:06:39

标签: python python-2.7

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

对于上面的简单程序,stacktrace返回正确的行号,但是对于下面更复杂的方法,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

1 个答案:

答案 0 :(得分: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))