Debugging Python
Contents
|
|
Debugging Python with pdb 🐞
Console pdb
Debugging can be quite messy and annoying but pdb helps out. pdb is an out-of-the-box fully featured Python console to make use of any Python command. If you have a standard script to debug simply use
|
|
In-Code pdb
Unfortunately this doesn’t work for Python packages that you call via path variable, such as Instagram-Scraper. In this case either simply look for the respective file in your folder. For Instagram-Scraper on Ubuntu it would be:
|
|
Either put the following lines at the very beginning to start pdb right away or look for the lines you want to debug:
|
|
Save the file and execute as usual. When the code runs into bp() function you will get pdb console. Here Python oneliners come in handy!
Export string to file in one line
|
|
Otherwise just type interact
and you have a fully-featured Python console for statements over multiple lines. When finished, type quit()
and you get back to pdb.
Debugging fastAPI with pdb
If you tried to debug fastAPI via pdb in your console you might have stumbled upon the error message
|
|
Solution
That’s simply due to undefined __spec__
variable. The quickest workaround for debugging is simply setting it to None
in your app.py
for starting the app:
|
|
Note that you can also turn off the reload flag. Else, whenever you save any settings in your main.py or any imported files the whole server will restart.
fastAPI pdb
In your main code, simply import pdb and set the break point as usual:
|
|
In your console, start app.py
as usual:
|
|
Et voilà: you’re in pdb.
In my case, I import another file with helper functions in main.py
. As I wanted to debug one of those functions, I simply imported pdb there and set the break point.
If you triggered the function with bp()
via the right request your console should jump right to this part of your code and allow you to access values or continue the execution with c
.