Skip to content
Advertisement

Print current call stack from a method in code

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

Advertisement

Answer

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

JavaScript

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

JavaScript

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

JavaScript

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

Advertisement