faulthandler — Dump the Python traceback¶
Added in version 3.3.
This module contains functions to dump Python tracebacks explicitly, on a fault,
after a timeout, or on a user signal. Call faulthandler.enable() to
install fault handlers for the SIGSEGV,
SIGFPE, SIGABRT, SIGBUS, and
SIGILL signals. You can also
enable them at startup by setting the PYTHONFAULTHANDLER environment
variable or by using the -X faulthandler command line option.
The fault handler is compatible with system fault handlers like Apport or the
Windows fault handler. The module uses an alternative stack for signal handlers
if the sigaltstack() function is available. This allows it to dump the
traceback even on a stack overflow.
The fault handler is called on catastrophic cases and therefore can only use signal-safe functions (e.g. it cannot allocate memory on the heap). Because of this limitation traceback dumping is minimal compared to normal Python tracebacks:
Only ASCII is supported. The
backslashreplaceerror handler is used on encoding.Each string is limited to 500 characters.
Only the filename, the function name and the line number are displayed. (no source code)
It is limited to 100 frames and 100 threads.
The order is reversed: the most recent call is shown first.
By default, the Python traceback is written to sys.stderr. To see
tracebacks, applications must be run in the terminal. A log file can
alternatively be passed to faulthandler.enable().
The module is implemented in C, so tracebacks can be dumped on a crash or when Python is deadlocked.
The Python Development Mode calls faulthandler.enable()
at Python startup.
See also
Dumping the traceback¶
- faulthandler.dump_traceback(file=sys.stderr, all_threads=True)¶
Dump the tracebacks of all threads into file. If all_threads is
False, dump only the current thread.See also
traceback.print_tb(), which can be used to print a traceback object.Changed in version 3.5: Added support for passing file descriptor to this function.
Dumping the C stack¶
Added in version 3.14.
- faulthandler.dump_c_stack(file=sys.stderr)¶
Dump the C stack trace of the current thread into file.
If the Python build does not support it or the operating system does not provide a stack trace, then this prints an error in place of a dumped C stack.
C Stack Compatibility¶
If the system does not support the C-level backtrace(3) or dladdr1(3), then C stack dumps will not work. An error will be printed instead of the stack.
Additionally, some compilers do not support CPython’s implementation of C stack dumps. As a result, a different error may be printed instead of the stack, even if the operating system supports dumping stacks.
Note
Dumping C stacks can be arbitrarily slow, depending on the DWARF level of the binaries in the call stack.
Fault handler state¶
- faulthandler.enable(file=sys.stderr, all_threads=True, c_stack=True)