I'm trying get all of the current stack frames and do some inspection on each frames f_globals
attribute for each frame. This is very similar to how the unittest
module does it except that in my case, an exception has not been thrown. traceback.extract_stack()
does not give access to this but the frame in sys.exc_info()
does when an exception is thrown.
Just use the "stack" function from the inspect module.
>>> import inspect
>>> inspect.stack()
[(<frame object at 0x02467FE0>, '<stdin>', 1, '<module>', None, None)]
This call yields a list, where each element is a tuple consisting of the running frame and extra information on that frame (according to Python docs):
[frame, filename, line number, function name, frame sources, current line index in sources]
To inspect f_globals
on each frame object:
>>> for frame_tuple in inspect.stack():
... print frame_tuple[0].f_globals.keys()
...
['frame_tuple', '__builtins__', 'inspect', '__package__', '__name__', 'readline', 'rlcompleter', '__doc__']
"stack" function is slow, though, to be used in actual running code for anything other than setting things up, or debugging. If you need to inspect the stack for some runtime operation - like fetching variable values, or other introspection-based code, do use inspect.currentframe()
to get the currentframe, and the .f_back
property on each frame for links to the previous frames - this is fast enough.
You should not use sys._getframe
, since, as the underscore at the start of the name indicates, it is not intended for public use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With