본문 바로가기
Python

faulthandler (파이썬 추적 백업 모듈)

by yororing 2024. 7. 5.

00 개요

  • 목적: 파이썬 파일들을 코드 분석 시 faulthandler라는 모듈을 import 한 후 faulthandler.enable() 하길래 이게 뭔지 정리하고자 함

 

01 faulthandler 모듈이란

1. 정의

  • dump the Python traceback → 파이썬 추적을 dump(백업)함
  • 3.3 버전에 추가됨
  • contains functions to dump Python tracebacks explicitly, on a fault 또는 after a timeout 또는 on a user signal.
  • 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 backslashreplace error 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.

2. faulthandler 활성화, 비활성화, 상태 확인

방법 1: Enable them at startup by setting the PYTHONFAULTHANDLER environment variable or by using the -X faulthandler command line option

방법 2: Call faulthandler.enable() to install fault handlers for the SIGSEGV, SIGFPE, SIGABRT, SIGBUS, and SIGILL signals.

faulthandler.enable(file=sys.stderr, all_threads=True) # 활성화

faulthandler.disable() # 비활성화: uninstall the signal handlers installed by enable()

faulthandler.is_enabled() # 상태 확인
  • Enable the fault handler: install handlers for the SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals to dump the Python traceback. 
  • If all_threads is True, produce tracebacks for every running thread. Otherwise, dump only the current thread. 
  • The file must be kept open until the fault handler is disabled:.

 

 참조

  1. https://docs.python.org/3/library/faulthandler.html#module-faulthandler
  2.  
  3.  
  4.