Example File: 14_breakpoint.py

Companion source example or verification log for the tutorial, preserved in full with user directory paths anonymized; actual execution scope is defined by the log itself.

# Demonstrate pdb non-interactively: feed a sequence of commands to the debugger and inspect variables at a breakpoint
import subprocess, sys, textwrap, pathlib, tempfile

target = textwrap.dedent('''
def accumulate(xs):
    total = 0
    for i, x in enumerate(xs):
        total += x * i
    return total
print("Result:", accumulate([5, 6, 7, 8]))
''')
path = pathlib.Path(tempfile.mkdtemp(prefix="tutorial-pdb-")) / "bp_demo.py"
path.write_text(target, encoding="utf-8")

commands = "\n".join([
    "b 5, i == 2",      # Conditional breakpoint: pause only when i == 2
    "c",                # Continue execution to the breakpoint
    "p i, x, total",    # Print variables
    "where",            # Inspect call stack
    "c",                # Continue until completion
    "q",
]) + "\n"
out = subprocess.run([sys.executable, "-X", "utf8", "-m", "pdb", str(path)], input=commands,
                     capture_output=True, text=True, encoding="utf-8", timeout=10)
print(out.stdout.replace(str(path), "bp_demo.py"))
Back to Tutorials Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram