Python › Debugging & Profiling

How would you use the 'faulthandler' module to diagnose a program that crashes with a segmentation fault, typically from a C extension?

Advanced

Answer

faulthandler.enable() registers handlers for fatal errors (like SIGSEGV) that dump a Python-level traceback to stderr before the process crashes — invaluable for diagnosing crashes originating in C extensions (like NumPy or a native library) that would otherwise crash silently with no useful Python-level diagnostic information.
import faulthandler
faulthandler.enable()

# If a C extension later causes a segfault, faulthandler prints a Python
# traceback showing exactly where in your Python code the crash occurred,
# instead of just silently terminating the process
Real-world example Diagnosing a mysterious crash in a data-processing script caused by a bug in a native C extension dependency.

Common follow-ups: How would you enable faulthandler automatically for EVERY Python process, without modifying your script's code?