Python Faulthandler Module
The faulthandler module contains functions to dump Python tracebacks explicitly, on a fault, after a timeout, or on a user signal. It is useful for debugging crashes like segmentation faults.
Importing the Module
import faulthandler
Enabling Faulthandler
To enable the fault handler, call enable(). This installs handlers for SIGSEGV, SIGFPE, SIGABRT, SIGBUS, and SIGILL to dump the traceback.
import faulthandler
faulthandler.enable()
Dumping Traceback Explicitly
You can dump the traceback of all threads explicitly.
import faulthandler
import sys
faulthandler.dump_traceback(file=sys.stdout, all_threads=True)
Dumping Traceback After a Timeout
You can schedule a traceback dump after a specific timeout (in seconds). This is useful for debugging deadlocks or infinite loops.
import faulthandler
import time
faulthandler.dump_traceback_later(timeout=2, repeat=False)
# Simulate a long-running task
time.sleep(3)
User Signals
You can register a signal to dump the traceback. (Note: SIGUSR1 is typically available on Unix systems).
import faulthandler
import signal
if hasattr(signal, 'SIGUSR1'):
faulthandler.register(signal.SIGUSR1)