Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I ignore a line when using the pdb?

Tags:

python

pdb

For some quick Python debugging I'll occasionally throw in a import pdb;pdb.set_trace() line that will drop me into the debugger. Very handy. However, if I want to debug a loop, that may run many, many, many times, it loses its effectiveness somewhat. I could mash on continue many, many, many times, but is there a way to remove/ignore that hard-coded breakpoint so I can let it finish?

I could set a global flag and run it conditionally, but then I'd lose the 'standalone-ness' of the one-line breakpoint, also requiring another flag for each pdb.set_trace().

like image 420
Nick T Avatar asked Oct 22 '22 13:10

Nick T


1 Answers

The following hack will disable all other calls to set_trace in current run (i.e., from anywhere in your code).

Create this noop_pdb drop-in:

# noop_pdb.py
def set_trace(*args, **kwargs):
    pass

Then, once your code breaks in the real pdb.set_trace, and you want to disable the rest of the calls to set_trace, do:

sys.modules['pdb'] = __import__('noop_pdb')

Next time the interpreter encounters a line like:

import pdb;pdb.set_trace()

It avoids re-importing the built-in pdb, picking up the drop-in.

EDIT: another way to implement this hack, which does not require noop_pdb, is by replacing set_trace with noop, instead of the whole pdb module: pdb.set_trace = lambda: None

like image 70
shx2 Avatar answered Oct 24 '22 03:10

shx2