1
2
3
import pdb
from pdb import set_trace as bp
bp()

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

1
python -m pdb your_script.py

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:

1
/home/user/miniconda3/lib/python3.7/site-packages/instagram_scraper/app.py

Either put the following lines at the very beginning to start pdb right away or look for the lines you want to debug:

1
2
3
import pdb
from pdb import set_trace as bp
bp()

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

1
open("out_file.txt", 'a').write(variable)

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

1
AttributeError: module '__main__' has no attribute '__spec__'

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:

1
2
3
4
5
import uvicorn

if __name__=="__main__":
    __spec__ = None
    uvicorn.run("main:app",host='0.0.0.0', port=8000, reload=True, debug=True)

Credits to SO.

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:

1
2
3
import pdb
from pdb import set_trace as bp
bp()

In your console, start app.py as usual:

1
python app.py

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.