Here's a comprehensive cheatsheet for Python's debugging capabilities:
# Insert at any point in your code
import pdb; pdb.set_trace() # Python 2 and 3
breakpoint() # Python 3.7+c/cont/continue: Continue execution until next breakpointn/next: Execute current line and move to next line (steps over function calls)s/step: Step into function callr/return: Continue execution until current function returnsq/quit: Exit the debugger
l/list: Show current position in codell/longlist: Show more context around current positionp expression: Print value of expressionpp expression: Pretty-print value of expressionwhatis expression: Print type of expressiondir(object): Show attributes of objectlocals(): Show all local variablesglobals(): Show all global variables
b/break: Set breakpoint at current lineb linenum: Set breakpoint at line numberb file.py:linenum: Set breakpoint in file at line numberb function: Set breakpoint at first line of functiondisable bpnum: Disable breakpoint numberenable bpnum: Enable breakpoint numberclear bpnum: Delete breakpoint numberclear: Delete all breakpoints
j linenum: Jump to line number (skips execution)unt/until: Continue until line with greater line number is reachedunt linenum: Continue execution until line numbera/args: Print arguments of current functionu/up: Move up one frame in the call stackd/down: Move down one frame in the call stackw/where: Print current call stackh/help: Show list of commandsh command: Show help for specific command!statement: Execute Python statement in current context
# Install with: pip install ipdb
import ipdb; ipdb.set_trace()IPython debugger has all PDB commands plus tab completion, syntax highlighting, and better printing of variables.
from IPython.core.debugger import set_trace
set_trace() # Or use %debug magic after an exception# In settings.py, set DEBUG=True
from django.conf import settings
if settings.DEBUG:
import pdb; pdb.set_trace()# Debug on exception
app.debug = True
# Or manual breakpoint
import pdb; pdb.set_trace()# Install with: pip install web-pdb
import web_pdb; web_pdb.set_trace() # Then open browser at http://localhost:5555Add this to .vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}Then use F5 to start debugging with breakpoints set in the editor.