Python Debugger: debugging-in-python-with-the-pdb-module
post-template-default,single,single-post,postid-3102,single-format-standard,bridge-core-2.9.4,qode-page-transition-enabled,ajax_fade,page_not_loaded,,qode-title-hidden,qode_grid_1300,footer_responsive_adv,hide_top_bar_on_mobile_header,qode-child-theme-ver-1.0.0,qode-theme-ver-27.8,qode-theme-bridge,qode_header_in_grid,wpb-js-composer js-comp-ver-6.7.0,vc_responsive,elementor-default,elementor-kit-2634

Debugging in Python with the PDB Module

The Pdb module(python debugger) comes built-in to the Python standard library. This module uses bdb(basic debugger functions) and cmd(support for line-oriented command interpreters) modules. The python debugger also works on command line which is a great advantage for debugging code on remote servers.

The module is already installed when you install python. Therefore, we only need to import it into our code to use its functionality.

The Pdb module supports the following;

  • Setting breakpoints
  • Stepping through code
  • Source code listing
  • Viewing stack traces

How to Invoke the Python Debugger

To establish debugging in our program, we first insert import pdb, pdb.set_trace() commands in our code. With python 3.7 or later versions, we can replace the set_trace() with the breakpoint() function rather.

Wherever the breakpoint() or set_trace() command is placed, the execution stops there. To run our program, we can use the python IDLE or the Visual Studio Code editor.

Using the command line, we can run the following command in terminal python -m pdb

Sample Program One

In this program, we want to compute an addition of different variables, we have added pdb.set_trace() at various locations in our code to know where error might occur. On running the program, we will find out it stopped and printed e=0.1 which tells us that particular line in our code hasn’t been executed yet.

Sample Program Two

In this program, we implemented a recursion function and also added the pdb.set_trace() at two different locations where our code will stop while debugging and we can pass in our variable using the print command.

We pass in the variable value here with the print keyword, which hereby prints the result.

Going forward, we can also run various commands on the terminal such as the c (continue execution), q (quit the debugger/execution), n(step to next line within the same function),s (step to next line in this function or a called function). using the help command, it shows us all the available functions and command available.

We can have access to variables executed in our program both local and global variables. There are different commands we can use to access this, such as printing all arguments of function defined and are still currently active. We can use (a), the p command can as well use for printing result.

No Comments

Post A Comment