pythonpdb

How can I force PDB to quit when the signal is being caught?


PDB's quit command works by raising an exception (Bdb.BdbQuit). If that exception gets caught, I cannot figure out a way to kill the program short of killing the entire shell. CTRL+C works by raising a KeyboardInterrupt exception, which can also be caught.

You can recreate this problem with this simple script.

foo = 0
while True:
    try:
        import pdb; pdb.set_trace()
        foo += 1
    except:
        pass

This script cannot be stopped from within PDB with the quit command or CTRL+C.

I'm aware this is bad programming and you should never use an except without an exception type. I ask because I ran into this issue while debugging and a third-party library trapped me in the loop.


Solution

  • You can try killing the python process with os._exit.

    import os
    try:
        print("Exiting")
        os._exit(1)
    except:
        print("Caught!")
    

    Output:

    Exiting