Question

I sometimes set breakpoints in deep loop code as follows:

import pdb; pdb.set_trace()

If I press c then it continues, but breaks again on the next iteration of the loop. Is there a way of clearing this breakpoint from within pdb? The b command doesn't list it.

Or is there a one liner I can insert into my Python source file that will set a 'soft' breakpoint that can be cleared?

Or ideally a one liner that sets the trace, then clears itself?


Edit: I'd be interested in any editor that lets you set breakpoints.

I currently run my script from emacs as follows:

M-x pdb
Run ~/.virtualenvs/.../python2.7/pdb.py (like this):
     ~/.virtualenvs/.../python2.7/pdb.py ~/start-myserver.py
Était-ce utile?

La solution

A one liner that sets the trace, then clears itself (overwrite with an empty function):

import pdb; pdb.set_trace(); pdb.set_trace = lambda: 0

Call reload(pdb) to restore pdb.set_trace. (imp.reload(pdb) in Python 3.x)

Autres conseils

Instead of setting the breakpoint using set_trace, you could set up and run the debugger manually. pdb.Pdb.set_break() takes an argument temprorary which will cause the breakpoint to be cleared the first time it's hit.

import pdb

def traced_function():
    for i in range(4):
        print(i)  # line 5

if __name__ == '__main__':
    import pdb
    p = pdb.Pdb()
    # set break on the print line (5):
    p.set_break(__file__, 5, temporary=True)
    p.run('traced_function()')

example output:

$ python pdb_example.py 
> <string>(1)<module>()
(Pdb) c
Deleted breakpoint 1 at /tmp/pdb_example.py:5
> /tmp/test.py(5)traced_function()
-> print(i)  # line 5
(Pdb) c
0
1
2
3

The same could be achieved by running the program using pdb from the command line, but setting it up like this allows you to preserve the breakpoints between invokations and not loosing them when exiting the debugger session.

Given that import pdb; pdb.set_trace() is a temporary line of code anyway I think it's easiest to simply use a boolean:

has_trace = True
for line in data:
    if has_trace:
        import pdb; pdb.set_trace()
        has_trace = False
    # ... other code here

Probably not what you want, but in emacs,

I can C-space to break and unbreak with some key(which I can't recall :()

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top