Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining stack frame

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 for print_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?

like image 399
max Avatar asked Mar 30 '12 06:03

max


3 Answers

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.

like image 159
kindall Avatar answered Jan 01 '23 11:01

kindall


This documentation gives information on functions you could use to get a stack frame, for example inspect.currentframe().

like image 42
orlp Avatar answered Jan 01 '23 12:01

orlp


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.

like image 34
xiaochen Avatar answered Jan 01 '23 12:01

xiaochen