set breakpoint in another module/file

Daniel millerdev at
Tue Sep 22 23:03:51 CEST 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/", "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,
    """set a breakpoint or a given line in file with conditional

        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)
            evaluate to true to break
        temp - if true, create a temporary breakpoint

    example usage:

        setbreak(42, "/path/to/", "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:
            mod = __import__(file[4:], globals(), locals(),
        except ImportError, err:
            if throw:
            sys.__stdout__.write("cannot set breakpoint: %s:%s : %s" %
                (file, line, err))
        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.curframe = frame
    pdb.botframe = object()
    temp = line
    while temp < line + 10:
        error = pdb.set_break(file, temp, cond=cond, temporary=temp)
        if error:
            temp += 1
    if error:
        error = pdb.set_break(file, line, cond=cond, temporary=temp)
        if throw:
            raise Error(error)
        sys.__stdout__.write("\n%s\n" % error)
    pdb.do_break("") # print breakpoints

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

~ Daniel

More information about the Python-list mailing list