Debugging Python with GDB on Ubuntu

Lets say you want to debug a python process that is either already running or crashing in native code. Pythons PDB is of no help here and you will have to use low-level GDB debugger. Fortunately, it comes with support for debugging high level python scripts.

However, while the actual python-gdb commands are nicely described here, that page lacks important details on how to get python-gdb in the first place. We are merely told that a python-gdb.py is needed.

On Ubuntu/ Debian, this file is included in the python3-dbg package:

sudo apt install python3.10-dbg

Installing that is sufficient, if you use the matching python3 package. You can go ahead and connect to some running python process via:

gdb -p <PID>
# verify that the script is loaded
(gdb) info auto-load
# get a python backtrace
(gdb) py-bt
Traceback (most recent call first):
  File "/usr/lib/python3.10/selectors.py", line 416, in select
    fd_event_list = self._selector.poll(timeout)
  File "/usr/lib/python3.10/socketserver.py", line 232, in serve_forever
...

In case Ubuntu is merely a host and you use coda, you can still use the host python-gdb.py – even if the python versions dont match. You will have to load the script manually though like:

(gdb) source /usr/share/gdb/auto-load/usr/bin/python3.10-gdb.py
Exit mobile version
%%footer%%