23

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?

user299648
  • 2,769
  • 6
  • 34
  • 43

4 Answers4

33

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • 9
    Notice that even with `''.join` you will get a multiline string, since the elements of `format_stack()` contain `\n`s. – Thomas Ahle Feb 12 '14 at 11:04
  • 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: https://stackoverflow.com/questions/62952273/how-to-catch-python-exception-and-save-traceback-text-as-string – phyatt Jul 11 '22 at 14:31
4

How about traceback.format_stack?

Stobor
  • 44,246
  • 6
  • 66
  • 69
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.

theodox
  • 12,028
  • 3
  • 23
  • 36
1

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

Chris Cogdon
  • 7,481
  • 5
  • 38
  • 30