set breakpoint in another module/file

Daniel millerdev at gmail.com
Tue Sep 22 17:03:51 EDT 2009


Is there a way with pdb to set a breakpoint in another module directly
using a command similar to set_trace() ? For example, I'd like to do
something like this in my source code:

import pdb
pdb.setbreak(42, "/path/to/universe.py", "name == 'hitchhiker'")

Is there a way to do (something like) that with the pdb that ships
with Python? If not, what would people think of adding an additional
function to the pdb module that would do something like the following
code (see below). My use case for this is that often I'd like to set a
breakpoint in some module that does not belong to the project I'm
working in. I rather not edit the module, which is often in site-
packages. The workaround of course is to use set_trace() to drop into
pdb and then set the breakpoint at the pdb prompt, but that's clumsy.
I've found this to be handy:


def setbreak(line=None, file=None, cond=None, temp=0, frame=None,
throw=False):
    """set a breakpoint or a given line in file with conditional

    arguments:
        line - line number on which to break
        file - module or filename where the breakpoint should be set
        cond - string with conditional expression, which (if given)
must
            evaluate to true to break
        temp - if true, create a temporary breakpoint

    example usage:

        setbreak(42, "/path/to/universe.py", "name == 'hitchhiker'")

    """
    if frame is None:
        frame = sys._getframe().f_back
    if file is None:
        file = frame.f_code.co_filename
    elif not file.startswith("file:") and os.path.sep not in file:
        try:
            mod = __import__(file[4:], globals(), locals(),
["__file__"])
        except ImportError, err:
            if throw:
                raise
            sys.__stdout__.write("cannot set breakpoint: %s:%s : %s" %
                (file, line, err))
            return
        file = mod.__file__
        sys.__stdout__.write("breaking in: %s" % file)
    if file.endswith(".pyc"):
        file = file[:-1]
    pdb = Pdb(stdout=sys.__stdout__) # use sys.__stdout__ to work with
nose tests
    pdb.reset()
    pdb.curframe = frame
    pdb.botframe = object()
    pdb.set_continue()
    temp = line
    while temp < line + 10:
        error = pdb.set_break(file, temp, cond=cond, temporary=temp)
        if error:
            temp += 1
        else:
            break
    if error:
        error = pdb.set_break(file, line, cond=cond, temporary=temp)
        if throw:
            raise Error(error)
        sys.__stdout__.write("\n%s\n" % error)
        return
    sys.__stdout__.write("\n")
    pdb.do_break("") # print breakpoints
    sys.settrace(pdb.trace_dispatch)


I'm sure there is a better way to implement some of this, especially
the part marked with HACK, but it seems to work for me in most
situations.

~ Daniel



More information about the Python-list mailing list