For python is there a way to print variables scope from context where exception happens?
You can use the function sys.exc_info()
to get the last exception that occurred in the current thread in you except clause. This will be a tuple of exception type, exception instance and traceback. The traceback is a linked list of frame. This is what is used to print the backtrace by the interpreter. It does contains the local dictionnary.
So you can do:
import sys
def f():
a = 1
b = 2
1/0
try:
f()
except:
exc_type, exc_value, tb = sys.exc_info()
if tb is not None:
prev = tb
curr = tb.tb_next
while curr is not None:
prev = curr
curr = curr.tb_next
print prev.tb_frame.f_locals
You have to first extract traceback, in your example something like this would print it:
except:
print sys.exc_traceback.tb_next.tb_frame.f_locals
I'm not sure about the tb_next, I would guess you have to go through the complete traceback, so something like this (untested):
except:
tb_last = sys.exc_traceback
while tb_last.tb_next:
tb_last = tb_last.tb_next
print tb_last.tb_frame.f_locals
Perhaps you're looking for locals() and globals()?