Reputation: 97
I have the following Python program:
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
For simple programs as above the stacktrace returns the correct line number, but for more complicated methods like below Python throws more stacktraces (the latest call being the last), is there a way to figure out the index of the stacktrace ex: formatted_lines[2]
to get the latest call.
try:
def prize():
print("hello")
def main():
prize()
Catch:
.....
any help would be appreciated.
Also tried this:
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)
I get an error on the last line "invalid syntax"
When I just try:
print (filename, lineno, line)
I get an error:
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
Upvotes: 0
Views: 1341
Reputation: 179412
Please don't try to parse stack traces using the output of format_exc
. That's only meant to produce a human-readable stack trace.
You should instead use linecache
to get the offending line:
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))
Upvotes: 1