DEV Community

loading...

Debugging Python applications (plus free cheat sheet)

flaviabastos profile image Flávia Bastos Originally published at flaviabastos.ca on ・2 min read

My primary debugging tool is to add print statements to my programs. Print statements are very easy to use and they work well for any simple scripts. But that’s the catch: if you’re debugging an application and/or a test file, print statements won’t be enough or will just not work (in the case if tests files).

For those cases, I find that pdb, the debugger that is part of Python’s standard library, is the next best thing: also very simple to use but gives you more insight on what’s going on in your program.

All you have to do is to invoke pdb to enter in debug mode. It’s possible to either call the script with pdb as in:

python3 -m pdb myscript.py

or call pdb inside the script where you want to stop regular execution and start debugging – for python 3.6 and older:

import pdb; pdb.set_trace() # python 3.6 and older

Or for python 3.7 and up:

breakpoint() # python 3.7

When in debugging mode you have access to the pbd console, where you can use pdb commands (listed below) and also inspect your script – like printing variable contents, for example (just type the variable’s name in the console).

Example:

    number = '123456' total = 0 import pdb; pdb.set\_trace() for nb in number: total += int(nb)

In the short script above, once the debugger console is launched, you can hit ‘n’ to reach the next line, then type ‘nb’ to read its value at that point of execution.

Personally, the most used pdb commands are the listed below but you can find the full list in the official documentation or in this free cheat sheet:

s(tep): Execute the current line, stop at the first possible occasion

c(ont(inue)): Continue execution, only stop when a breakpoint is encountered.

n(ext): Continue execution until the next line in the current function is reached or it returns

r(eturn): Continue execution until the current function returns.q(uit): Quit from the debugger. The program being executed is aborted.

The post Debugging Python applications (plus free cheat sheet) was originally published at flaviabastos.ca

Discussion

pic
Editor guide