Skip to content

Instantly share code, notes, and snippets.

@hotohoto
Created October 7, 2020 04:45
Show Gist options
  • Save hotohoto/98297e70f290f1940530517f01aeacd7 to your computer and use it in GitHub Desktop.
Save hotohoto/98297e70f290f1940530517f01aeacd7 to your computer and use it in GitHub Desktop.
Python stack dumper
import signal
import threading
import traceback
import time
import sys
def func2():
y = 2
time.sleep(1)
def func1():
x = 3
func2()
def get_all_local_variables(frame):
stack_frames = []
while frame is not None:
stack_frames.append(frame)
frame = frame.f_back
stack_frames.reverse()
return [f.f_locals for f in stack_frames]
def print_all_frame_info():
id2name = dict([(th.ident, th.name) for th in threading.enumerate()])
outputs = []
for thread_id, frame in sys._current_frames().items():
outputs.append("\n# Thread: %s(%d)" % (id2name.get(thread_id, ""), thread_id))
is_same_thread = thread_id == threading.get_ident()
all_local_vars = get_all_local_variables(frame)
stacks = traceback.extract_stack(frame)
for i, ((filename, lineno, name, line), local_vars) in enumerate(
zip(stacks, all_local_vars)
):
if is_same_thread and i >= len(all_local_vars) - 1:
local_vars = None
outputs.append('File: "%s", line %d, in %s' % (filename, lineno, name))
if line:
outputs.append(" %s" % (line.strip()))
if local_vars is not None:
outputs.append(" %s" % local_vars)
print("\n".join(outputs))
def handler(sig_num, _current_frame):
print("signal handler called with signal", sig_num)
print_all_frame_info()
signal.signal(signal.SIGUSR1, handler)
for i in range(10000000):
# print(i)
func1()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment