簡體   English   中英

Python Stacktrace模塊回溯行錯誤

[英]Python stacktrace module traceback line error

我有以下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會拋出更多的stacktrace(最后一次調用是最后一個),有沒有辦法找出stacktrace的索引,例如: 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

請不要嘗試使用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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM