brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: faulthandler.dump_traceback_later shows where a script hangs

Python
~/tips/tip-python-faulthandler-dump-traceback-later

import faulthandler

Prints the traceback of every thread after a timeout, so a hung script shows where it is stuck.

A script that just sits there is hard to debug because it prints no error. A timer can make Python show where it is stuck.

faulthandler.dump_traceback_later(timeout) dumps the tracebacks of all threads after timeout seconds. With exit=True it then ends the process with status 1:

import faulthandler
faulthandler.dump_traceback_later(30, exit=True)

main()

If main() hangs in a function called slow(), the output after 30 seconds looks like this:

Timeout (0:00:30)!
Thread 0x00007f0dbe2ab080 (most recent call first):
  File "script.py", line 5 in slow
  File "script.py", line 8 in main
  File "script.py", line 10 in <module>

Add repeat=True to dump every 30 seconds instead of once, which helps when you want to see whether the script moves at all. The file argument sends the dump somewhere other than sys.stderr, but the docs say that file must stay open until the dump happens or the timer is cancelled. Calling the function a second time replaces the earlier settings and resets the timer.

Caveats: the docs note that exit=True calls _exit(), which ends the process immediately without cleanup such as flushing file buffers. Keep it out of code that is writing important files. When the slow part is over, call faulthandler.cancel_dump_traceback_later() so the timer does not fire later.

Further reading: faulthandler

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link