Explain Codes LogoExplain Codes Logo

How to execute multi-line statements within Python's own debugger (PDB)

python
prompt-engineering
debugging
pdb
Alex KataevbyAlex Kataev·Dec 15, 2024
TLDR

To execute multi-line code in pdb, use the exec command, like so:

(Pdb) exec("for i in range(5): print(i)")

This example prints numbers from 0 to 4, all within one single line.

For interactive Python sessions, within a PDB debugger, you can enter !import code; code.interact(local=vars()). Use Ctrl-D to get back to the PDB prompt after your session, and Ctrl-C to abort the entire PDB session.

Executing multi-line statements in PDB

Interactive sessions within PDB

To simulate a full-fledged Python environment inside PDB and increase debugging efficiency, enter the following command for an interactive Python session:

(Pdb) !import code; code.interact(local=vars())

Exiting interactive sessions

When you are done with the multi-line editing, hit Ctrl-D to exit the interactive session and return to the PDB prompt. Terminate the entire PDB session with Ctrl-C.

Inline execution of multiple commands

You want to run several commands simultaneously? No worries! Use ; to separate commands on the same line within PDB:

(pdb) !x=0; y=10; print(f'x + y = {x + y}, because math')

Execute multiple commands at breakpoints

To execute a sequence of commands at a particular breakpoint, use commands command in PDB and conclude your input with end when you're done:

(pdb) break 23 (pdb) commands (Pdb) print('Breakpoint reached. What a breakneck speed!') (Pdb) inspect_variables() (Pdb) end

Use (pdb) help commands for guidance on implementing multi-line execution at specific breakpoints.

iPython PDB enhancements

Enjoy scripting in iPython's PDB, which offers more fluid and dynamic execution for multi-line statements.

Advanced practices and tips

Looping and conditional constructs

The exec command can handle complex multi-line constructs involving loops and conditional blocks. Just remember to indent your lines appropriately.

(Pdb) exec("""\ if x > 10: # If x walks into a bar... for i in range(x): # ...for the next x rounds... print(i) # ...x has to buy a round for everyone! """)

Defining functions in pdb

You can also define entire functions while in pdb! Test new functions on the fly during your debugging session:

(Pdb) exec(""" def test_function(arg): return arg * 2 # Because two wrongs do make a right! In Python, at least... """)

Beware of gotchas

Keep an eye on proper quotation and escaping when using exec to avert syntax issues. Also, exec touches the current namespace, so your variable manipulations will persist in the PDB environment!