次の 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