For some time I’ve wanted the equivalent of Java’s ability to dump the stack trace of all currently running threads in Python as a means for debugging some hung processes. I finally found a solution and wired it up to the services’ http console:
import sys
import traceback
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
def stacktraces():
code = []
for threadId, stack in sys._current_frames().items():
code.append("\n# ThreadID: %s" % threadId)
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
if line:
code.append(" %s" % (line.strip()))
return highlight("\n".join(code), PythonLexer(), HtmlFormatter(
full=False,
# style="native",
noclasses=True))
The magic happens with sys._current_frames()
which returns exactly what I wanted. The only outstanding issue is how to get the thread’s name to display in addition to the ident.
I’ll probably hook this up as a signal handler as well so headless applications can have the same functionality.