How do I get a stack frame to pass into traceback.print_stack
?
From Python 3.3a1 docs:
traceback.print_stack(f=None, limit=None, file=None)
This function prints a stack trace from its invocation point. The optional
f
argument can be used to specify an alternate stack frame to start. The optional limit and file arguments have the same meaning as forprint_exception()
.
But nowhere in the docs did I find a way to actually obtain a stack frame. To be specific, let's say I want to print the stack trace starting one level above the invocation point. How can I do that?
inspect.stack()
will get you the current stack as a list. You can pick any frame you want out of it. You can also do e.g. inspect.currentframe().f_back
to get your caller's frame. Basically, the inspect
module is where it's at.
This documentation gives information on functions you could use to get a stack frame, for example inspect.currentframe()
.
In addition to inspect module, you can try:
import sys
sys._getframe(1)
or
import sys
sys._getframe().f_back
Be warned it is a private function, some versions of python may not implement it.
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