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: python -m trace -t prints every line as your script runs it

Python
~/tips/tip-python-m-trace-every-line

python3 -m trace -t script.py

Watch the exact path a script takes through its code, line by line.

Sometimes I don’t need a debugger, I just want to see which way the code went. Python ships with a tracer that prints each line as it executes, a bit like bash -x.

python3 -m trace -t script.py
python3 -m trace -t --ignore-dir="$(python3 -c 'import sys; print(sys.base_prefix)')" script.py

For a tiny script with a function f the output looks like this:

 --- modulename: script, funcname: f
script.py(2):     if x > 1:
script.py(3):         return "big"

You see each function you enter and every line with its number. That makes questions like “why does it never reach the else branch” easy to answer without adding print statements.

On anything that imports modules the output explodes, because it traces the standard library too. The second command uses --ignore-dir to skip everything under Python’s own install, so you only see your own files. Expect to pipe the result into less or grep anyway.

It’s slow, so it suits short runs. The same module also does coverage counting with -c, but for that I’d use a proper coverage tool. For a quick look at the path through a few hundred lines, though, it’s handy.

Further reading: trace module

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