How to execute multi-line statements within Python's own debugger (PDB)
To execute multi-line code in pdb
, use the exec
command, like so:
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:
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:
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:
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.
Defining functions in pdb
You can also define entire functions while in pdb
! Test new functions on the fly during your debugging session:
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!
Was this article helpful?