Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print current call stack from a method in Python code

In Python, how can I print the current call stack from within a method (for debugging purposes).

like image 988
oneself Avatar asked Jul 20 '09 21:07

oneself


People also ask

How do I get the call stack in Python?

If you use python debugger, not only interactive probing of variables but you can get the call stack with the "where" command or "w".

What is current call stack in Python?

The Python interpreter uses a call stack to run a Python program. When a function is called in Python, a new frame is pushed onto the call stack for its local execution, and every time a function call returns, its frame is popped off the call stack.

What are function should be used to get a printout of the current call stack?

Description. By default traceback() prints the call stack of the last uncaught error, i.e., the sequence of calls that lead to the error. This is useful when an error occurs with an unidentifiable error message. It can also be used to print the current stack or arbitrary lists of calls.


1 Answers

Here's an example of getting the stack via the traceback module, and printing it:

import traceback  def f():     g()  def g():     for line in traceback.format_stack():         print(line.strip())  f()  # Prints: # File "so-stack.py", line 10, in <module> #     f() # File "so-stack.py", line 4, in f #     g() # File "so-stack.py", line 7, in g #     for line in traceback.format_stack(): 

If you really only want to print the stack to stderr, you can use:

traceback.print_stack() 

Or to print to stdout (useful if want to keep redirected output together), use:

traceback.print_stack(file=sys.stdout) 

But getting it via traceback.format_stack() lets you do whatever you like with it.

like image 183
RichieHindle Avatar answered Oct 06 '22 01:10

RichieHindle