25

traceback.format_exc()

can get it with raising an exception.

traceback.print_stack()

prints the stack without an exception needed, but it does not return a string.

There doesn't seem to be a way to get the stack trace string without raising an exception in python?

4 Answers 4

34

It's traceback.extract_stack() if you want convenient access to module and function names and line numbers, or ''.join(traceback.format_stack()) if you just want a string that looks like the traceback.print_stack() output.

Sign up to request clarification or add additional context in comments.

2 Comments

Notice that even with ''.join you will get a multiline string, since the elements of format_stack() contain \ns.
The stacktrace I got in my app with format_stack had many layers I wasn't interested in and would never get picked up by the normal debugger. format_exception had less noise for me in a Flask app and looked closer to the normal stack dumps in my running output: stackoverflow.com/questions/62952273/…
4

How about traceback.format_stack?

Comments

2

Use the inspect module. In particular, inspect. currentframe() -- but the whole module is there for the purpose of looking at the state of your program at a given time.

Some useful inspect tricks here.

Comments

1

Also try the "py-spy" module, which can connect to a python process and get the instantaneous stack dump.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.