Interesting question. Apparently you can use sys.exc_info(), which is described at http://docs.python.org/library/sys.html. The line numbers are in the traceback.tb_lineno variables. A little example shows how you can use it.
import sys
def test(n):
m = 1/(n-3)
print(n, m)
return
def testall(list):
for n in list:
try:
test(n)
except ZeroDivisionError as errmsg:
print("ZeroDivisionError: %s" % errmsg)
except Exception as errmsg:
print("Unexpected error: %s" % errmsg)
(type, value, traceback) = sys.exc_info()
print(" type:", type)
print(" value:", value)
followTrace(traceback, 5)
return
def followTrace(traceback, depth):
if not traceback or depth < 0:
return
print("traceback:", traceback)
print(" tb_frame:", traceback.tb_frame)
print(" tb_lasti:", traceback.tb_lasti)
print(" tb_lineno:", traceback.tb_lineno)
print(" tb_next:", traceback.tb_next)
followTrace(traceback.tb_next, depth-1)
return
try:
testall([1,2,3,4,"a"])
finally:
print("Apparently necessary to delete circular references")
There is some warning that assigning the traceback to a local variable cause circular references which cannot be garbage-collected. The try-finally block takes care of that.
What i can extract from that code is, that the frame is the “context” where the script executes and it only exists at runtime, so is the traceback objects.
sys.exc_info() returns None after the execution, so i dont know which is the error line after the execution. And thats what im trying to achieve.
Ill keep trying exploring the sys, traceback and inspect modules. Maybe i can find something like last traceback or last frame there.
The last error type is sys.last_value but thats not the info im looking for.