0

我有以下 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 会抛出更多的堆栈跟踪(最近的调用是最后一个),有没有办法找出堆栈跟踪的索引 ex: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
4

1 回答 1

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))
于 2012-10-15T05:53:16.953 回答