Dump stacktraces of all active Threads Dump stacktraces of all active Threads python python

Dump stacktraces of all active Threads


As jitter points out in an earlier answer sys._current_frames() gives you what you need for v2.5+. For the lazy the following code snippet worked for me and may help you:

print >> sys.stderr, "\n*** STACKTRACE - START ***\n"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()))for line in code:    print >> sys.stderr, lineprint >> sys.stderr, "\n*** STACKTRACE - END ***\n"


For Python 3.3 and later, there is faulthandler.dump_traceback().

The code below produces similar output, but includes the thread name and could be enhanced to print more information.

for th in threading.enumerate():    print(th)    traceback.print_stack(sys._current_frames()[th.ident])    print()


When using Zope, you want to install Products.signalstack or mr.freeze; these were designed for just this purpose!

Send a USR1 signal to your Zope server and it'll immediately dump stack traces for all threads to the console. It'll do this even if all Zope threads are locked up.

Under the hood these packages indirectly use threadframes; for Python versions 2.5 and up, when not using Zope, you can build the same functionality using the sys._current_frames() function to access per-thread stack frames.

As of Zope 2.12.5 this functionality is integrated into Zope itself, and there is no need to install additional packages anymore.