This will be a short port of the most useful diagnostics you can inspect while running the Pdb debugger.
Pdb is the de facto debugger for Python scripts, with commands similar to GDB. Many Python developers use Pdb in order to diagnose an abrupt exception, or to see the internal state of their variables while their scripts run.
The minimum code to debug a function:
>>> import pdb >>> import mymodule >>> pdb.run('mymodule.test()')
The functions or code you want to debug has to be already imported in a module.
python3 -m pdb myscript.py
To arbitrarily break into the debugger, put this statement in the place of your script you want it to break at:
The following function enters the debugger using the last exception raised as the stack:
At any rate, when the debugger enters you will arrive at a command prompt that looks like
(Pdb). Sometimes you will be at the first statement and you either need to
step into a function, step (
next) over one, or set a
help to print a list of commands, or to print the documentation of a single command. Other basic commands are
p to print a variable,
pp to pretty-print it,
locals() (a Python function) shows you the list of variables, and
ll to list the source code of the entire function you're in.
down moves you up and down the call stack respectively, allowing you to view the variables in that local scope.
where prints a traceback with an arrow pointing at the frame in the call stake you're currently in.
For this, you need to enter a recursive debugger. Using
debug function_call(), you will get a clean state that lets you step through execution or set breakpoints, letting you print variables in the process.
The easiest way is when the breakpoint is a line in the current file, then you can just type
break LINE_NUMBER. It is also possible to break in a different file if you give it the absolute path such as
To avoid the hassle of spelling out the full path each time, add part of the folder into
sys.path while you're in the debugger:
sys.path.append("/home/pythonuser/src/") break script.py:42
The last point I want to go over is how to get the traceback information without raising the exception again or entering a debugger. This can be done using the
traceback module and the exception's
import traceback traceback.print_tb(e.__traceback__)
I hope you learned something new from this post. If you see any errors, please let me know so I can correct them.