One minute
The ugly ways to debug Python
So you have your Python program.
And it’s hanging somewhere.
You add print("I am here")
around, but soon you get lost.
If only there was something like gdb and ctrl+c
…
pdb enters the game
The Python debugger can help with this, but what if your script is somehow called by other scripts? Or maybe it’s a library you want to debug?
You can add this little snippet somewhere in your code:
def debug_signal_handler(signal, frame):
import pdb
pdb.set_trace()
import signal
signal.signal(signal.SIGUSR1, debug_signal_handler)
Then run your program, and
pkill -SIGUSR1 <your program name>
Or, better:
sudo ps -elf | grep <your program name>
And then
kill -SIGUSR1 <the PID from above>
You can surely script this up to be less ugly!
The iPython way
I usually find it hard to debug the data-structures. For sure there are better tools, but when you have an hammer, all problems are nails. So, add
from IPython import embed
embed()
where you want your program to stop. It will open an interactive shell, and from there you can run any command as they where written in your script.