#Python advice for learning the pdb debugger:
Start with just breakpoint() and a small subset of the commands:
l/list
s/step
n/next
p <expr>
pp vars()
Launch from run(), pm(), or the command line.
Occasionally, read the docs to add a new command to your repertoire.
Start with just breakpoint() and a small subset of the commands:
l/list
s/step
n/next
p <expr>
pp vars()
Launch from run(), pm(), or the command line.
Occasionally, read the docs to add a new command to your repertoire.
For starters, try using "s" several times to step through simple standard library code.
>>> import pdb
>>> import random
>>> http://pdb.run ('random.randrange(10, 20)')
> <string>(1)<module>()->None
(Pdb) s
(Pdb) s
(Pdb) s
(Pdb) s
(Pdb) l
(Pdb) pp vars()
(Pdb) quit
>>> import pdb
>>> import random
>>> http://pdb.run ('random.randrange(10, 20)')
> <string>(1)<module>()->None
(Pdb) s
(Pdb) s
(Pdb) s
(Pdb) s
(Pdb) l
(Pdb) pp vars()
(Pdb) quit
To run from the command-line:
$ python3.8 -m pdb some_buggy_module
$ python3.8 -m pdb some_buggy_module
You can launch pdb after an exception occurs:
>>> def mean(iterator):
s = sum(iterator)
n = len(iterator)
return s / n
>>> mean(iter(range(5)))
Traceback (most recent call last):
...
>>> import pdb; http://pdb.pm ()
> <pyshell#13>(3)mean()
(Pdb) list
>>> def mean(iterator):
s = sum(iterator)
n = len(iterator)
return s / n
>>> mean(iter(range(5)))
Traceback (most recent call last):
...
>>> import pdb; http://pdb.pm ()
> <pyshell#13>(3)mean()
(Pdb) list
Or put breakpoint() directly in a critical section of code:
def mean(iterator):
s = sum(iterator)
breakpoint() # Triggers pdb at this point
n = len(iterator)
return s / n
def mean(iterator):
s = sum(iterator)
breakpoint() # Triggers pdb at this point
n = len(iterator)
return s / n
When you're ready for a little more, try "u" and "d" commands to move up and down nested stack frames. I aways immediately then use "l" to show me where I am in the chain of function calls.
Help is available, though it is somewhat terse
(Pdb) ? <== Lists all commands
(Pdb) ? alias <== Help on a single command
(Pdb) ? <== Lists all commands
(Pdb) ? alias <== Help on a single command
Have fun with it. Your skills with grow quickly.
Tame your expectations though. Debuggers don't debug. They make the invisible visible, but actual debugging still requires thinking and insight.
Tame your expectations though. Debuggers don't debug. They make the invisible visible, but actual debugging still requires thinking and insight.
One other thing: Not all code is amenable to debugging with pdb().
For event driven systems, the logging module is your new best friend.
Also, C code is opaque to pdb. You'll need more advanced tooling for that.
For event driven systems, the logging module is your new best friend.
Also, C code is opaque to pdb. You'll need more advanced tooling for that.