# Buggy code
def _run_with_debugger(self, code, code_ns, filename=None, bp_line=None, bp_file=None):
    """
    Run `code` in debugger with a break point.

    Parameters
    ----------
    code : str
        Code to execute.
    code_ns : dict
        A namespace in which `code` is executed.
    filename : str
        `code` is ran as if it is in `filename`.
    bp_line : int, optional
        Line number of the break point.
    bp_file : str, optional
        Path to the file in which break point is specified.
        `filename` is used if not given.

    Raises
    ------
    UsageError
        If the break point given by `bp_line` is not valid.

    """
    deb = debugger.Pdb(self.shell.colors)
    # reset Breakpoint state, which is moronically kept
    # in a class
    bdb.Breakpoint.next = 1
    bdb.Breakpoint.bplist = {}
    bdb.Breakpoint.bpbynumber = [None]
    if bp_line is not None:
        # Set an initial breakpoint to stop execution
        maxtries = 10
        bp_file = bp_file or filename
        checkline = deb.checkline(bp_file, bp_line)
        if not checkline:
            for bp in range(bp_line + 1, bp_line + maxtries + 1):
                if deb.checkline(bp_file, bp):
                    break
            else:
                msg = (
                    "\nI failed to find a valid line to set "
                    "a breakpoint\n"
                    "after trying up to line: %s.\n"
                    "Please set a valid breakpoint manually "
                    "with the -b option." % bp
                )
                raise UsageError(msg)
        # if we find a good linenumber, set the breakpoint
        deb.do_break("%s:%s" % (bp_file, bp_line))

    if filename:
        # Mimic Pdb._runscript(...)
        deb._wait_for_mainpyfile = True
        deb.mainpyfile = deb.canonic(filename)

    # Start file run
    print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
    try:
        if filename:
            # save filename so it can be used by methods on the deb object
            deb._exec_filename = filename
        deb.run(code, code_ns)

    except:
        etype, value, tb = sys.exc_info()
        # Skip three frames in the traceback: the %run one,
        # one inside bdb.py, and the command-line typed by the
        # user (run by exec in pdb itself).
        self.shell.InteractiveTB(etype, value, tb, tb_offset=3)


# Traceback (AttributeError)
In [1]: %run -d ~/t.py
Breakpoint 1 at /home/sk/t.py:1
NOTE: Enter 'c' at the ipdb>  prompt to start your script.
/home/sk/t.py(1)<module>()
1---> 1 from sympy import *
2 x = Symbol('x')
3 #bessely(0,x).series(x)

ipdb> n
/home/sk/t.py(2)<module>()
1     1 from sympy import *
----> 2 x = Symbol('x')
3 #bessely(0,x).series(x)

ipdb> n
/home/sk/t.py(5)<module>()
4 #sin(asin(3), evaluate=False).is_rational
----> 5 n = Symbol('n', integer=True)
6 #Sum(x**n, (n, 0, S.Infinity)).doit()

ipdb> restart
---------------------------------------------------------------------------
Restart                                   Traceback (most recent call last)
/home/sk/src/ipython/IPython/utils/py3compat.pyc in execfile(fname, *where)
181             else:
182                 filename = fname
--> 183             __builtin__.execfile(filename, *where)

/home/sk/t.py in <module>()
3 #bessely(0,x).series(x)
4 #sin(asin(3), evaluate=False).is_rational
----> 5 n = Symbol('n', integer=True)
6 #Sum(x**n, (n, 0, S.Infinity)).doit()
7 summation(2**n - 10,(n,0,oo))

/home/sk/t.py in <module>()
3 #bessely(0,x).series(x)
4 #sin(asin(3), evaluate=False).is_rational
----> 5 n = Symbol('n', integer=True)
6 #Sum(x**n, (n, 0, S.Infinity)).doit()
7 summation(2**n - 10,(n,0,oo))

/usr/lib/python2.6/bdb.pyc in trace_dispatch(self, frame, event, arg)
44             return # None
45         if event == 'line':
---> 46             return self.dispatch_line(frame)
47         if event == 'call':
48             return self.dispatch_call(frame, arg)

/usr/lib/python2.6/bdb.pyc in dispatch_line(self, frame)
62     def dispatch_line(self, frame):
63         if self.stop_here(frame) or self.break_here(frame):
---> 64             self.user_line(frame)
65             if self.quitting: raise BdbQuit
66         return self.trace_dispatch

/usr/lib/python2.6/pdb.pyc in user_line(self, frame)
148             self._wait_for_mainpyfile = 0
149         if self.bp_commands(frame):
--> 150             self.interaction(frame, None)
151
152     def bp_commands(self,frame):

/home/sk/src/ipython/IPython/core/debugger.pyc in interaction(self, frame, traceback)
259     def interaction(self, frame, traceback):
260         self.shell.set_completer_frame(frame)
--> 261         OldPdb.interaction(self, frame, traceback)
262
263     def new_do_up(self, arg):

/usr/lib/python2.6/pdb.pyc in interaction(self, frame, traceback)
196         self.setup(frame, traceback)
197         self.print_stack_entry(self.stack[self.curindex])
--> 198         self.cmdloop()
199         self.forget()
200

/usr/lib/python2.6/cmd.pyc in cmdloop(self, intro)
140                             line = line.rstrip('\r\n')
141                 line = self.precmd(line)
--> 142                 stop = self.onecmd(line)
143                 stop = self.postcmd(stop, line)
144             self.postloop()

/usr/lib/python2.6/pdb.pyc in onecmd(self, line)
265         """
266         if not self.commands_defining:
--> 267             return cmd.Cmd.onecmd(self, line)
268         else:
269             return self.handle_command_def(line)

/usr/lib/python2.6/cmd.pyc in onecmd(self, line)
217             except AttributeError:
218                 return self.default(line)
--> 219             return func(arg)
220
221     def emptyline(self):

/usr/lib/python2.6/pdb.pyc in do_run(self, arg)
659             sys.argv = shlex.split(arg)
660             sys.argv[:0] = argv0
--> 661         raise Restart
662
663     do_restart = do_run

Restart:

In [2]:

# Fixed code
def _run_with_debugger(self, code, code_ns, filename=None, bp_line=None, bp_file=None):
    """
    Run `code` in debugger with a break point.

    Parameters
    ----------
    code : str
        Code to execute.
    code_ns : dict
        A namespace in which `code` is executed.
    filename : str
        `code` is ran as if it is in `filename`.
    bp_line : int, optional
        Line number of the break point.
    bp_file : str, optional
        Path to the file in which break point is specified.
        `filename` is used if not given.

    Raises
    ------
    UsageError
        If the break point given by `bp_line` is not valid.

    """
    deb = debugger.Pdb(self.shell.colors)
    # reset Breakpoint state, which is moronically kept
    # in a class
    bdb.Breakpoint.next = 1
    bdb.Breakpoint.bplist = {}
    bdb.Breakpoint.bpbynumber = [None]
    if bp_line is not None:
        # Set an initial breakpoint to stop execution
        maxtries = 10
        bp_file = bp_file or filename
        checkline = deb.checkline(bp_file, bp_line)
        if not checkline:
            for bp in range(bp_line + 1, bp_line + maxtries + 1):
                if deb.checkline(bp_file, bp):
                    break
            else:
                msg = (
                    "\nI failed to find a valid line to set "
                    "a breakpoint\n"
                    "after trying up to line: %s.\n"
                    "Please set a valid breakpoint manually "
                    "with the -b option." % bp
                )
                raise UsageError(msg)
        # if we find a good linenumber, set the breakpoint
        deb.do_break("%s:%s" % (bp_file, bp_line))

    if filename:
        # Mimic Pdb._runscript(...)
        deb._wait_for_mainpyfile = True
        deb.mainpyfile = deb.canonic(filename)

    # Start file run
    print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
    try:
        if filename:
            # save filename so it can be used by methods on the deb object
            deb._exec_filename = filename
        while True:
            try:
                deb.run(code, code_ns)
            except Restart:
                print("Restarting")
                if filename:
                    deb._wait_for_mainpyfile = True
                    deb.mainpyfile = deb.canonic(filename)
                continue
            else:
                break

    except:
        etype, value, tb = sys.exc_info()
        # Skip three frames in the traceback: the %run one,
        # one inside bdb.py, and the command-line typed by the
        # user (run by exec in pdb itself).
        self.shell.InteractiveTB(etype, value, tb, tb_offset=3)