How to debug Python scripts and API code in the console and in VS Code
Debugging is an important step in Python programming, whether you are a Python data scientist or software developer. It can be fairly straightforward to debug simple Python scripts. However, it is more advanced to debug Python API code, especially with VS Code. In this article, the most common ways to debug Python scripts and API code are introduced, both in the console and in VS Code. You shall then be fairly clear about which tools to use and how to use them in your practical work.
How to debug Python scripts with pdb in the console?
In the repo cloned, there is a simple script called
python_script.py, where the command line arguments are simply echoed:
To debug a script, the most “naive” way is to use
To use pdb for debugging, we need to set some breakpoints in the code. A classical way is to use the following snippet:
import pdb; pdb.set_trace()
You can add breakpoints anywhere you like in the code. Normally you would put the breakpoints at the places where you think there may be bugs. Then you can run the script to trigger the breakpoints. For this script, the command is:
$ python python_script.py 1 2 3 --even --level WARNING
Note that if you want to open a terminal inside VS Code and run the script there, you can do so by clicking “Terminal” => “New Terminal”.
The output is like this:
arg = 1
arg = 2
arg = 3
key = even, value = True
key = level, value = WARNING
With the breakpoints, you can check the code logic and data flow, as well as the values for the variables. Checking the values of…