Created
April 25, 2022 17:22
-
-
Save rgov/d0557ebc42639783ae43f0ceb32840d8 to your computer and use it in GitHub Desktop.
trace all the python things
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# why the heck are you crashing suddenly | |
import datetime | |
import functools | |
import threading | |
import traceback | |
import os | |
import signal | |
import sys | |
def signal_handler(prev_handler, signum, frame): | |
print( | |
datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S.%f'), | |
f'caught signal {signum}' | |
) | |
if callable(prev_handler): | |
prev_handler(signum, frame) | |
elif prev_handler == signal.SIG_DFL: | |
this = signal.signal(signum, signal.SIG_DFL) | |
os.kill(os.getpid(), signum) # or signal.raise_signal() in Py >= 3.8 | |
signal.signal(signum, this) | |
catchable_sigs = set(signal.Signals) - {signal.SIGKILL, signal.SIGSTOP} | |
for sig in catchable_sigs: | |
prev_handler = signal.getsignal(sig) | |
signal.signal(sig, functools.partial(signal_handler, prev_handler)) | |
def trace(frame, event, arg): | |
if event == 'line': | |
stack = traceback.extract_stack(frame, 1)[0] | |
print( | |
datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S.%f'), | |
f'[{threading.get_ident()}]', | |
f'{stack.filename}:{stack.lineno}', | |
stack.line | |
) | |
return trace | |
threading.settrace(trace) | |
sys.settrace(trace) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment