Python Debugger
lastmod 2024-09-03created 2018-07-1910 edits
The module pdb defines an interactive source code debugger for Python programs. It supports setting (conditional) breakpoints and single stepping at the source line level, inspection of stack frames, source code listing, and evaluation of arbitrary Python code in the context of any stack frame. It also supports post-mortem debugging and can be called under program control.
The debugger is extensible – it is actually defined as the class Pdb. This is currently undocumented but easily understood by reading the source. The extension interface uses the modules bdb and cmd.
How to use
To debug the test.py file, run it as follows.
To set a breakpoint in the code:
Example
The debugger’s prompt is (Pdb). Typical usage to run a program under control of the debugger is:
>>> import pdb
>>> import mymodule
>>> pdb.run('mymodule.test()')
> <string>(0)?()
(Pdb) continue
> <string>(1)?()
(Pdb) continue
NameError: 'spam'
> <string>(1)?()
(Pdb)
Stacktrace
Using a command:
Using Python:traceback:
Using Python:inspect:
Syntaxhighlight
Take a look at pdb++ - it is a drop-in replacement for pdb that fills all your requirements and adds some other nice features such as tab completion and new commands such as watch and sticky.
Here is a sample config file that will enable colours (add this after creating the file: touch ~/.pdbrc.py):
import pdb
class Config(pdb.DefaultConfig):
use_pygments = True
pygments_formatter_class = "pygments.formatters.TerminalTrueColorFormatter"
pygments_formatter_kwargs = {"style": "monokai"}