1#!/usr/local/bin/python3.7
2
3"""
4The Python Debugger Pdb
5=======================
6
7To use the debugger in its simplest form:
8
9        >>> import pdb
10        >>> pdb.run('<a statement>')
11
12The debugger's prompt is '(Pdb) '.  This will stop in the first
13function call in <a statement>.
14
15Alternatively, if a statement terminated with an unhandled exception,
16you can use pdb's post-mortem facility to inspect the contents of the
17traceback:
18
19        >>> <a statement>
20        <exception traceback>
21        >>> import pdb
22        >>> pdb.pm()
23
24The commands recognized by the debugger are listed in the next
25section.  Most can be abbreviated as indicated; e.g., h(elp) means
26that 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel',
27nor as 'H' or 'Help' or 'HELP').  Optional arguments are enclosed in
28square brackets.  Alternatives in the command syntax are separated
29by a vertical bar (|).
30
31A blank line repeats the previous command literally, except for
32'list', where it lists the next 11 lines.
33
34Commands that the debugger doesn't recognize are assumed to be Python
35statements and are executed in the context of the program being
36debugged.  Python statements can also be prefixed with an exclamation
37point ('!').  This is a powerful way to inspect the program being
38debugged; it is even possible to change variables or call functions.
39When an exception occurs in such a statement, the exception name is
40printed but the debugger's state is not changed.
41
42The debugger supports aliases, which can save typing.  And aliases can
43have parameters (see the alias help entry) which allows one a certain
44level of adaptability to the context under examination.
45
46Multiple commands may be entered on a single line, separated by the
47pair ';;'.  No intelligence is applied to separating the commands; the
48input is split at the first ';;', even if it is in the middle of a
49quoted string.
50
51If a file ".pdbrc" exists in your home directory or in the current
52directory, it is read in and executed as if it had been typed at the
53debugger prompt.  This is particularly useful for aliases.  If both
54files exist, the one in the home directory is read first and aliases
55defined there can be overridden by the local file.  This behavior can be
56disabled by passing the "readrc=False" argument to the Pdb constructor.
57
58Aside from aliases, the debugger is not directly programmable; but it
59is implemented as a class from which you can derive your own debugger
60class, which you can make as fancy as you like.
61
62
63Debugger commands
64=================
65
66"""
67# NOTE: the actual command documentation is collected from docstrings of the
68# commands and is appended to __doc__ after the class has been defined.
69
70import os
71import re
72import sys
73import cmd
74import bdb
75import dis
76import code
77import glob
78import pprint
79import signal
80import inspect
81import traceback
82import linecache
83
84
85class Restart(Exception):
86    """Causes a debugger to be restarted for the debugged python program."""
87    pass
88
89__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
90           "post_mortem", "help"]
91
92def find_function(funcname, filename):
93    cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
94    try:
95        fp = open(filename)
96    except OSError:
97        return None
98    # consumer of this info expects the first line to be 1
99    with fp:
100        for lineno, line in enumerate(fp, start=1):
101            if cre.match(line):
102                return funcname, filename, lineno
103    return None
104
105def getsourcelines(obj):
106    lines, lineno = inspect.findsource(obj)
107    if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
108        # must be a module frame: do not try to cut a block out of it
109        return lines, 1
110    elif inspect.ismodule(obj):
111        return lines, 1
112    return inspect.getblock(lines[lineno:]), lineno+1
113
114def lasti2lineno(code, lasti):
115    linestarts = list(dis.findlinestarts(code))
116    linestarts.reverse()
117    for i, lineno in linestarts:
118        if lasti >= i:
119            return lineno
120    return 0
121
122
123class _rstr(str):
124    """String that doesn't quote its repr."""
125    def __repr__(self):
126        return self
127
128
129# Interaction prompt line will separate file and call info from code
130# text using value of line_prefix string.  A newline and arrow may
131# be to your liking.  You can set it once pdb is imported using the
132# command "pdb.line_prefix = '\n% '".
133# line_prefix = ': '    # Use this to get the old situation back
134line_prefix = '\n-> '   # Probably a better default
135
136class Pdb(bdb.Bdb, cmd.Cmd):
137
138    _previous_sigint_handler = None
139
140    def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None,
141                 nosigint=False, readrc=True):
142        bdb.Bdb.__init__(self, skip=skip)
143        cmd.Cmd.__init__(self, completekey, stdin, stdout)
144        if stdout:
145            self.use_rawinput = 0
146        self.prompt = '(Pdb) '
147        self.aliases = {}
148        self.displaying = {}
149        self.mainpyfile = ''
150        self._wait_for_mainpyfile = False
151        self.tb_lineno = {}
152        # Try to load readline if it exists
153        try:
154            import readline
155            # remove some common file name delimiters
156            readline.set_completer_delims(' \t\n`@#$%^&*()=+[{]}\\|;:\'",<>?')
157        except ImportError:
158            pass
159        self.allow_kbdint = False
160        self.nosigint = nosigint
161
162        # Read ~/.pdbrc and ./.pdbrc
163        self.rcLines = []
164        if readrc:
165            try:
166                with open(os.path.expanduser('~/.pdbrc')) as rcFile:
167                    self.rcLines.extend(rcFile)
168            except OSError:
169                pass
170            try:
171                with open(".pdbrc") as rcFile:
172                    self.rcLines.extend(rcFile)
173            except OSError:
174                pass
175
176        self.commands = {} # associates a command list to breakpoint numbers
177        self.commands_doprompt = {} # for each bp num, tells if the prompt
178                                    # must be disp. after execing the cmd list
179        self.commands_silent = {} # for each bp num, tells if the stack trace
180                                  # must be disp. after execing the cmd list
181        self.commands_defining = False # True while in the process of defining
182                                       # a command list
183        self.commands_bnum = None # The breakpoint number for which we are
184                                  # defining a list
185
186    def sigint_handler(self, signum, frame):
187        if self.allow_kbdint:
188            raise KeyboardInterrupt
189        self.message("\nProgram interrupted. (Use 'cont' to resume).")
190        self.set_step()
191        self.set_trace(frame)
192
193    def reset(self):
194        bdb.Bdb.reset(self)
195        self.forget()
196
197    def forget(self):
198        self.lineno = None
199        self.stack = []
200        self.curindex = 0
201        self.curframe = None
202        self.tb_lineno.clear()
203
204    def setup(self, f, tb):
205        self.forget()
206        self.stack, self.curindex = self.get_stack(f, tb)
207        while tb:
208            # when setting up post-mortem debugging with a traceback, save all
209            # the original line numbers to be displayed along the current line
210            # numbers (which can be different, e.g. due to finally clauses)
211            lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti)
212            self.tb_lineno[tb.tb_frame] = lineno
213            tb = tb.tb_next
214        self.curframe = self.stack[self.curindex][0]
215        # The f_locals dictionary is updated from the actual frame
216        # locals whenever the .f_locals accessor is called, so we
217        # cache it here to ensure that modifications are not overwritten.
218        self.curframe_locals = self.curframe.f_locals
219        return self.execRcLines()
220
221    # Can be executed earlier than 'setup' if desired
222    def execRcLines(self):
223        if not self.rcLines:
224            return
225        # local copy because of recursion
226        rcLines = self.rcLines
227        rcLines.reverse()
228        # execute every line only once
229        self.rcLines = []
230        while rcLines:
231            line = rcLines.pop().strip()
232            if line and line[0] != '#':
233                if self.onecmd(line):
234                    # if onecmd returns True, the command wants to exit
235                    # from the interaction, save leftover rc lines
236                    # to execute before next interaction
237                    self.rcLines += reversed(rcLines)
238                    return True
239
240    # Override Bdb methods
241
242    def user_call(self, frame, argument_list):
243        """This method is called when there is the remote possibility
244        that we ever need to stop in this function."""
245        if self._wait_for_mainpyfile:
246            return
247        if self.stop_here(frame):
248            self.message('--Call--')
249            self.interaction(frame, None)
250
251    def user_line(self, frame):
252        """This function is called when we stop or break at this line."""
253        if self._wait_for_mainpyfile:
254            if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
255                or frame.f_lineno <= 0):
256                return
257            self._wait_for_mainpyfile = False
258        if self.bp_commands(frame):
259            self.interaction(frame, None)
260
261    def bp_commands(self, frame):
262        """Call every command that was set for the current active breakpoint
263        (if there is one).
264
265        Returns True if the normal interaction function must be called,
266        False otherwise."""
267        # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
268        if getattr(self, "currentbp", False) and \
269               self.currentbp in self.commands:
270            currentbp = self.currentbp
271            self.currentbp = 0
272            lastcmd_back = self.lastcmd
273            self.setup(frame, None)
274            for line in self.commands[currentbp]:
275                self.onecmd(line)
276            self.lastcmd = lastcmd_back
277            if not self.commands_silent[currentbp]:
278                self.print_stack_entry(self.stack[self.curindex])
279            if self.commands_doprompt[currentbp]:
280                self._cmdloop()
281            self.forget()
282            return
283        return 1
284
285    def user_return(self, frame, return_value):
286        """This function is called when a return trap is set here."""
287        if self._wait_for_mainpyfile:
288            return
289        frame.f_locals['__return__'] = return_value
290        self.message('--Return--')
291        self.interaction(frame, None)
292
293    def user_exception(self, frame, exc_info):
294        """This function is called if an exception occurs,
295        but only if we are to stop at or just below this level."""
296        if self._wait_for_mainpyfile:
297            return
298        exc_type, exc_value, exc_traceback = exc_info
299        frame.f_locals['__exception__'] = exc_type, exc_value
300
301        # An 'Internal StopIteration' exception is an exception debug event
302        # issued by the interpreter when handling a subgenerator run with
303        # 'yield from' or a generator controlled by a for loop. No exception has
304        # actually occurred in this case. The debugger uses this debug event to
305        # stop when the debuggee is returning from such generators.
306        prefix = 'Internal ' if (not exc_traceback
307                                    and exc_type is StopIteration) else ''
308        self.message('%s%s' % (prefix,
309            traceback.format_exception_only(exc_type, exc_value)[-1].strip()))
310        self.interaction(frame, exc_traceback)
311
312    # General interaction function
313    def _cmdloop(self):
314        while True:
315            try:
316                # keyboard interrupts allow for an easy way to cancel
317                # the current command, so allow them during interactive input
318                self.allow_kbdint = True
319                self.cmdloop()
320                self.allow_kbdint = False
321                break
322            except KeyboardInterrupt:
323                self.message('--KeyboardInterrupt--')
324
325    # Called before loop, handles display expressions
326    def preloop(self):
327        displaying = self.displaying.get(self.curframe)
328        if displaying:
329            for expr, oldvalue in displaying.items():
330                newvalue = self._getval_except(expr)
331                # check for identity first; this prevents custom __eq__ to
332                # be called at every loop, and also prevents instances whose
333                # fields are changed to be displayed
334                if newvalue is not oldvalue and newvalue != oldvalue:
335                    displaying[expr] = newvalue
336                    self.message('display %s: %r  [old: %r]' %
337                                 (expr, newvalue, oldvalue))
338
339    def interaction(self, frame, traceback):
340        # Restore the previous signal handler at the Pdb prompt.
341        if Pdb._previous_sigint_handler:
342            signal.signal(signal.SIGINT, Pdb._previous_sigint_handler)
343            Pdb._previous_sigint_handler = None
344        if self.setup(frame, traceback):
345            # no interaction desired at this time (happens if .pdbrc contains
346            # a command like "continue")
347            self.forget()
348            return
349        self.print_stack_entry(self.stack[self.curindex])
350        self._cmdloop()
351        self.forget()
352
353    def displayhook(self, obj):
354        """Custom displayhook for the exec in default(), which prevents
355        assignment of the _ variable in the builtins.
356        """
357        # reproduce the behavior of the standard displayhook, not printing None
358        if obj is not None:
359            self.message(repr(obj))
360
361    def default(self, line):
362        if line[:1] == '!': line = line[1:]
363        locals = self.curframe_locals
364        globals = self.curframe.f_globals
365        try:
366            code = compile(line + '\n', '<stdin>', 'single')
367            save_stdout = sys.stdout
368            save_stdin = sys.stdin
369            save_displayhook = sys.displayhook
370            try:
371                sys.stdin = self.stdin
372                sys.stdout = self.stdout
373                sys.displayhook = self.displayhook
374                exec(code, globals, locals)
375            finally:
376                sys.stdout = save_stdout
377                sys.stdin = save_stdin
378                sys.displayhook = save_displayhook
379        except:
380            exc_info = sys.exc_info()[:2]
381            self.error(traceback.format_exception_only(*exc_info)[-1].strip())
382
383    def precmd(self, line):
384        """Handle alias expansion and ';;' separator."""
385        if not line.strip():
386            return line
387        args = line.split()
388        while args[0] in self.aliases:
389            line = self.aliases[args[0]]
390            ii = 1
391            for tmpArg in args[1:]:
392                line = line.replace("%" + str(ii),
393                                      tmpArg)
394                ii += 1
395            line = line.replace("%*", ' '.join(args[1:]))
396            args = line.split()
397        # split into ';;' separated commands
398        # unless it's an alias command
399        if args[0] != 'alias':
400            marker = line.find(';;')
401            if marker >= 0:
402                # queue up everything after marker
403                next = line[marker+2:].lstrip()
404                self.cmdqueue.append(next)
405                line = line[:marker].rstrip()
406        return line
407
408    def onecmd(self, line):
409        """Interpret the argument as though it had been typed in response
410        to the prompt.
411
412        Checks whether this line is typed at the normal prompt or in
413        a breakpoint command list definition.
414        """
415        if not self.commands_defining:
416            return cmd.Cmd.onecmd(self, line)
417        else:
418            return self.handle_command_def(line)
419
420    def handle_command_def(self, line):
421        """Handles one command line during command list definition."""
422        cmd, arg, line = self.parseline(line)
423        if not cmd:
424            return
425        if cmd == 'silent':
426            self.commands_silent[self.commands_bnum] = True
427            return # continue to handle other cmd def in the cmd list
428        elif cmd == 'end':
429            self.cmdqueue = []
430            return 1 # end of cmd list
431        cmdlist = self.commands[self.commands_bnum]
432        if arg:
433            cmdlist.append(cmd+' '+arg)
434        else:
435            cmdlist.append(cmd)
436        # Determine if we must stop
437        try:
438            func = getattr(self, 'do_' + cmd)
439        except AttributeError:
440            func = self.default
441        # one of the resuming commands
442        if func.__name__ in self.commands_resuming:
443            self.commands_doprompt[self.commands_bnum] = False
444            self.cmdqueue = []
445            return 1
446        return
447
448    # interface abstraction functions
449
450    def message(self, msg):
451        print(msg, file=self.stdout)
452
453    def error(self, msg):
454        print('***', msg, file=self.stdout)
455
456    # Generic completion functions.  Individual complete_foo methods can be
457    # assigned below to one of these functions.
458
459    def _complete_location(self, text, line, begidx, endidx):
460        # Complete a file/module/function location for break/tbreak/clear.
461        if line.strip().endswith((':', ',')):
462            # Here comes a line number or a condition which we can't complete.
463            return []
464        # First, try to find matching functions (i.e. expressions).
465        try:
466            ret = self._complete_expression(text, line, begidx, endidx)
467        except Exception:
468            ret = []
469        # Then, try to complete file names as well.
470        globs = glob.glob(text + '*')
471        for fn in globs:
472            if os.path.isdir(fn):
473                ret.append(fn + '/')
474            elif os.path.isfile(fn) and fn.lower().endswith(('.py', '.pyw')):
475                ret.append(fn + ':')
476        return ret
477
478    def _complete_bpnumber(self, text, line, begidx, endidx):
479        # Complete a breakpoint number.  (This would be more helpful if we could
480        # display additional info along with the completions, such as file/line
481        # of the breakpoint.)
482        return [str(i) for i, bp in enumerate(bdb.Breakpoint.bpbynumber)
483                if bp is not None and str(i).startswith(text)]
484
485    def _complete_expression(self, text, line, begidx, endidx):
486        # Complete an arbitrary expression.
487        if not self.curframe:
488            return []
489        # Collect globals and locals.  It is usually not really sensible to also
490        # complete builtins, and they clutter the namespace quite heavily, so we
491        # leave them out.
492        ns = self.curframe.f_globals.copy()
493        ns.update(self.curframe_locals)
494        if '.' in text:
495            # Walk an attribute chain up to the last part, similar to what
496            # rlcompleter does.  This will bail if any of the parts are not
497            # simple attribute access, which is what we want.
498            dotted = text.split('.')
499            try:
500                obj = ns[dotted[0]]
501                for part in dotted[1:-1]:
502                    obj = getattr(obj, part)
503            except (KeyError, AttributeError):
504                return []
505            prefix = '.'.join(dotted[:-1]) + '.'
506            return [prefix + n for n in dir(obj) if n.startswith(dotted[-1])]
507        else:
508            # Complete a simple name.
509            return [n for n in ns.keys() if n.startswith(text)]
510
511    # Command definitions, called by cmdloop()
512    # The argument is the remaining string on the command line
513    # Return true to exit from the command loop
514
515    def do_commands(self, arg):
516        """commands [bpnumber]
517        (com) ...
518        (com) end
519        (Pdb)
520
521        Specify a list of commands for breakpoint number bpnumber.
522        The commands themselves are entered on the following lines.
523        Type a line containing just 'end' to terminate the commands.
524        The commands are executed when the breakpoint is hit.
525
526        To remove all commands from a breakpoint, type commands and
527        follow it immediately with end; that is, give no commands.
528
529        With no bpnumber argument, commands refers to the last
530        breakpoint set.
531
532        You can use breakpoint commands to start your program up
533        again.  Simply use the continue command, or step, or any other
534        command that resumes execution.
535
536        Specifying any command resuming execution (currently continue,
537        step, next, return, jump, quit and their abbreviations)
538        terminates the command list (as if that command was
539        immediately followed by end).  This is because any time you
540        resume execution (even with a simple next or step), you may
541        encounter another breakpoint -- which could have its own
542        command list, leading to ambiguities about which list to
543        execute.
544
545        If you use the 'silent' command in the command list, the usual
546        message about stopping at a breakpoint is not printed.  This
547        may be desirable for breakpoints that are to print a specific
548        message and then continue.  If none of the other commands
549        print anything, you will see no sign that the breakpoint was
550        reached.
551        """
552        if not arg:
553            bnum = len(bdb.Breakpoint.bpbynumber) - 1
554        else:
555            try:
556                bnum = int(arg)
557            except:
558                self.error("Usage: commands [bnum]\n        ...\n        end")
559                return
560        self.commands_bnum = bnum
561        # Save old definitions for the case of a keyboard interrupt.
562        if bnum in self.commands:
563            old_command_defs = (self.commands[bnum],
564                                self.commands_doprompt[bnum],
565                                self.commands_silent[bnum])
566        else:
567            old_command_defs = None
568        self.commands[bnum] = []
569        self.commands_doprompt[bnum] = True
570        self.commands_silent[bnum] = False
571
572        prompt_back = self.prompt
573        self.prompt = '(com) '
574        self.commands_defining = True
575        try:
576            self.cmdloop()
577        except KeyboardInterrupt:
578            # Restore old definitions.
579            if old_command_defs:
580                self.commands[bnum] = old_command_defs[0]
581                self.commands_doprompt[bnum] = old_command_defs[1]
582                self.commands_silent[bnum] = old_command_defs[2]
583            else:
584                del self.commands[bnum]
585                del self.commands_doprompt[bnum]
586                del self.commands_silent[bnum]
587            self.error('command definition aborted, old commands restored')
588        finally:
589            self.commands_defining = False
590            self.prompt = prompt_back
591
592    complete_commands = _complete_bpnumber
593
594    def do_break(self, arg, temporary = 0):
595        """b(reak) [ ([filename:]lineno | function) [, condition] ]
596        Without argument, list all breaks.
597
598        With a line number argument, set a break at this line in the
599        current file.  With a function name, set a break at the first
600        executable line of that function.  If a second argument is
601        present, it is a string specifying an expression which must
602        evaluate to true before the breakpoint is honored.
603
604        The line number may be prefixed with a filename and a colon,
605        to specify a breakpoint in another file (probably one that
606        hasn't been loaded yet).  The file is searched for on
607        sys.path; the .py suffix may be omitted.
608        """
609        if not arg:
610            if self.breaks:  # There's at least one
611                self.message("Num Type         Disp Enb   Where")
612                for bp in bdb.Breakpoint.bpbynumber:
613                    if bp:
614                        self.message(bp.bpformat())
615            return
616        # parse arguments; comma has lowest precedence
617        # and cannot occur in filename
618        filename = None
619        lineno = None
620        cond = None
621        comma = arg.find(',')
622        if comma > 0:
623            # parse stuff after comma: "condition"
624            cond = arg[comma+1:].lstrip()
625            arg = arg[:comma].rstrip()
626        # parse stuff before comma: [filename:]lineno | function
627        colon = arg.rfind(':')
628        funcname = None
629        if colon >= 0:
630            filename = arg[:colon].rstrip()
631            f = self.lookupmodule(filename)
632            if not f:
633                self.error('%r not found from sys.path' % filename)
634                return
635            else:
636                filename = f
637            arg = arg[colon+1:].lstrip()
638            try:
639                lineno = int(arg)
640            except ValueError:
641                self.error('Bad lineno: %s' % arg)
642                return
643        else:
644            # no colon; can be lineno or function
645            try:
646                lineno = int(arg)
647            except ValueError:
648                try:
649                    func = eval(arg,
650                                self.curframe.f_globals,
651                                self.curframe_locals)
652                except:
653                    func = arg
654                try:
655                    if hasattr(func, '__func__'):
656                        func = func.__func__
657                    code = func.__code__
658                    #use co_name to identify the bkpt (function names
659                    #could be aliased, but co_name is invariant)
660                    funcname = code.co_name
661                    lineno = code.co_firstlineno
662                    filename = code.co_filename
663                except:
664                    # last thing to try
665                    (ok, filename, ln) = self.lineinfo(arg)
666                    if not ok:
667                        self.error('The specified object %r is not a function '
668                                   'or was not found along sys.path.' % arg)
669                        return
670                    funcname = ok # ok contains a function name
671                    lineno = int(ln)
672        if not filename:
673            filename = self.defaultFile()
674        # Check for reasonable breakpoint
675        line = self.checkline(filename, lineno)
676        if line:
677            # now set the break point
678            err = self.set_break(filename, line, temporary, cond, funcname)
679            if err:
680                self.error(err)
681            else:
682                bp = self.get_breaks(filename, line)[-1]
683                self.message("Breakpoint %d at %s:%d" %
684                             (bp.number, bp.file, bp.line))
685
686    # To be overridden in derived debuggers
687    def defaultFile(self):
688        """Produce a reasonable default."""
689        filename = self.curframe.f_code.co_filename
690        if filename == '<string>' and self.mainpyfile:
691            filename = self.mainpyfile
692        return filename
693
694    do_b = do_break
695
696    complete_break = _complete_location
697    complete_b = _complete_location
698
699    def do_tbreak(self, arg):
700        """tbreak [ ([filename:]lineno | function) [, condition] ]
701        Same arguments as break, but sets a temporary breakpoint: it
702        is automatically deleted when first hit.
703        """
704        self.do_break(arg, 1)
705
706    complete_tbreak = _complete_location
707
708    def lineinfo(self, identifier):
709        failed = (None, None, None)
710        # Input is identifier, may be in single quotes
711        idstring = identifier.split("'")
712        if len(idstring) == 1:
713            # not in single quotes
714            id = idstring[0].strip()
715        elif len(idstring) == 3:
716            # quoted
717            id = idstring[1].strip()
718        else:
719            return failed
720        if id == '': return failed
721        parts = id.split('.')
722        # Protection for derived debuggers
723        if parts[0] == 'self':
724            del parts[0]
725            if len(parts) == 0:
726                return failed
727        # Best first guess at file to look at
728        fname = self.defaultFile()
729        if len(parts) == 1:
730            item = parts[0]
731        else:
732            # More than one part.
733            # First is module, second is method/class
734            f = self.lookupmodule(parts[0])
735            if f:
736                fname = f
737            item = parts[1]
738        answer = find_function(item, fname)
739        return answer or failed
740
741    def checkline(self, filename, lineno):
742        """Check whether specified line seems to be executable.
743
744        Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
745        line or EOF). Warning: testing is not comprehensive.
746        """
747        # this method should be callable before starting debugging, so default
748        # to "no globals" if there is no current frame
749        globs = self.curframe.f_globals if hasattr(self, 'curframe') else None
750        line = linecache.getline(filename, lineno, globs)
751        if not line:
752            self.message('End of file')
753            return 0
754        line = line.strip()
755        # Don't allow setting breakpoint at a blank line
756        if (not line or (line[0] == '#') or
757             (line[:3] == '"""') or line[:3] == "'''"):
758            self.error('Blank or comment')
759            return 0
760        return lineno
761
762    def do_enable(self, arg):
763        """enable bpnumber [bpnumber ...]
764        Enables the breakpoints given as a space separated list of
765        breakpoint numbers.
766        """
767        args = arg.split()
768        for i in args:
769            try:
770                bp = self.get_bpbynumber(i)
771            except ValueError as err:
772                self.error(err)
773            else:
774                bp.enable()
775                self.message('Enabled %s' % bp)
776
777    complete_enable = _complete_bpnumber
778
779    def do_disable(self, arg):
780        """disable bpnumber [bpnumber ...]
781        Disables the breakpoints given as a space separated list of
782        breakpoint numbers.  Disabling a breakpoint means it cannot
783        cause the program to stop execution, but unlike clearing a
784        breakpoint, it remains in the list of breakpoints and can be
785        (re-)enabled.
786        """
787        args = arg.split()
788        for i in args:
789            try:
790                bp = self.get_bpbynumber(i)
791            except ValueError as err:
792                self.error(err)
793            else:
794                bp.disable()
795                self.message('Disabled %s' % bp)
796
797    complete_disable = _complete_bpnumber
798
799    def do_condition(self, arg):
800        """condition bpnumber [condition]
801        Set a new condition for the breakpoint, an expression which
802        must evaluate to true before the breakpoint is honored.  If
803        condition is absent, any existing condition is removed; i.e.,
804        the breakpoint is made unconditional.
805        """
806        args = arg.split(' ', 1)
807        try:
808            cond = args[1]
809        except IndexError:
810            cond = None
811        try:
812            bp = self.get_bpbynumber(args[0].strip())
813        except IndexError:
814            self.error('Breakpoint number expected')
815        except ValueError as err:
816            self.error(err)
817        else:
818            bp.cond = cond
819            if not cond:
820                self.message('Breakpoint %d is now unconditional.' % bp.number)
821            else:
822                self.message('New condition set for breakpoint %d.' % bp.number)
823
824    complete_condition = _complete_bpnumber
825
826    def do_ignore(self, arg):
827        """ignore bpnumber [count]
828        Set the ignore count for the given breakpoint number.  If
829        count is omitted, the ignore count is set to 0.  A breakpoint
830        becomes active when the ignore count is zero.  When non-zero,
831        the count is decremented each time the breakpoint is reached
832        and the breakpoint is not disabled and any associated
833        condition evaluates to true.
834        """
835        args = arg.split()
836        try:
837            count = int(args[1].strip())
838        except:
839            count = 0
840        try:
841            bp = self.get_bpbynumber(args[0].strip())
842        except IndexError:
843            self.error('Breakpoint number expected')
844        except ValueError as err:
845            self.error(err)
846        else:
847            bp.ignore = count
848            if count > 0:
849                if count > 1:
850                    countstr = '%d crossings' % count
851                else:
852                    countstr = '1 crossing'
853                self.message('Will ignore next %s of breakpoint %d.' %
854                             (countstr, bp.number))
855            else:
856                self.message('Will stop next time breakpoint %d is reached.'
857                             % bp.number)
858
859    complete_ignore = _complete_bpnumber
860
861    def do_clear(self, arg):
862        """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]]
863        With a space separated list of breakpoint numbers, clear
864        those breakpoints.  Without argument, clear all breaks (but
865        first ask confirmation).  With a filename:lineno argument,
866        clear all breaks at that line in that file.
867        """
868        if not arg:
869            try:
870                reply = input('Clear all breaks? ')
871            except EOFError:
872                reply = 'no'
873            reply = reply.strip().lower()
874            if reply in ('y', 'yes'):
875                bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp]
876                self.clear_all_breaks()
877                for bp in bplist:
878                    self.message('Deleted %s' % bp)
879            return
880        if ':' in arg:
881            # Make sure it works for "clear C:\foo\bar.py:12"
882            i = arg.rfind(':')
883            filename = arg[:i]
884            arg = arg[i+1:]
885            try:
886                lineno = int(arg)
887            except ValueError:
888                err = "Invalid line number (%s)" % arg
889            else:
890                bplist = self.get_breaks(filename, lineno)
891                err = self.clear_break(filename, lineno)
892            if err:
893                self.error(err)
894            else:
895                for bp in bplist:
896                    self.message('Deleted %s' % bp)
897            return
898        numberlist = arg.split()
899        for i in numberlist:
900            try:
901                bp = self.get_bpbynumber(i)
902            except ValueError as err:
903                self.error(err)
904            else:
905                self.clear_bpbynumber(i)
906                self.message('Deleted %s' % bp)
907    do_cl = do_clear # 'c' is already an abbreviation for 'continue'
908
909    complete_clear = _complete_location
910    complete_cl = _complete_location
911
912    def do_where(self, arg):
913        """w(here)
914        Print a stack trace, with the most recent frame at the bottom.
915        An arrow indicates the "current frame", which determines the
916        context of most commands.  'bt' is an alias for this command.
917        """
918        self.print_stack_trace()
919    do_w = do_where
920    do_bt = do_where
921
922    def _select_frame(self, number):
923        assert 0 <= number < len(self.stack)
924        self.curindex = number
925        self.curframe = self.stack[self.curindex][0]
926        self.curframe_locals = self.curframe.f_locals
927        self.print_stack_entry(self.stack[self.curindex])
928        self.lineno = None
929
930    def do_up(self, arg):
931        """u(p) [count]
932        Move the current frame count (default one) levels up in the
933        stack trace (to an older frame).
934        """
935        if self.curindex == 0:
936            self.error('Oldest frame')
937            return
938        try:
939            count = int(arg or 1)
940        except ValueError:
941            self.error('Invalid frame count (%s)' % arg)
942            return
943        if count < 0:
944            newframe = 0
945        else:
946            newframe = max(0, self.curindex - count)
947        self._select_frame(newframe)
948    do_u = do_up
949
950    def do_down(self, arg):
951        """d(own) [count]
952        Move the current frame count (default one) levels down in the
953        stack trace (to a newer frame).
954        """
955        if self.curindex + 1 == len(self.stack):
956            self.error('Newest frame')
957            return
958        try:
959            count = int(arg or 1)
960        except ValueError:
961            self.error('Invalid frame count (%s)' % arg)
962            return
963        if count < 0:
964            newframe = len(self.stack) - 1
965        else:
966            newframe = min(len(self.stack) - 1, self.curindex + count)
967        self._select_frame(newframe)
968    do_d = do_down
969
970    def do_until(self, arg):
971        """unt(il) [lineno]
972        Without argument, continue execution until the line with a
973        number greater than the current one is reached.  With a line
974        number, continue execution until a line with a number greater
975        or equal to that is reached.  In both cases, also stop when
976        the current frame returns.
977        """
978        if arg:
979            try:
980                lineno = int(arg)
981            except ValueError:
982                self.error('Error in argument: %r' % arg)
983                return
984            if lineno <= self.curframe.f_lineno:
985                self.error('"until" line number is smaller than current '
986                           'line number')
987                return
988        else:
989            lineno = None
990        self.set_until(self.curframe, lineno)
991        return 1
992    do_unt = do_until
993
994    def do_step(self, arg):
995        """s(tep)
996        Execute the current line, stop at the first possible occasion
997        (either in a function that is called or in the current
998        function).
999        """
1000        self.set_step()
1001        return 1
1002    do_s = do_step
1003
1004    def do_next(self, arg):
1005        """n(ext)
1006        Continue execution until the next line in the current function
1007        is reached or it returns.
1008        """
1009        self.set_next(self.curframe)
1010        return 1
1011    do_n = do_next
1012
1013    def do_run(self, arg):
1014        """run [args...]
1015        Restart the debugged python program. If a string is supplied
1016        it is split with "shlex", and the result is used as the new
1017        sys.argv.  History, breakpoints, actions and debugger options
1018        are preserved.  "restart" is an alias for "run".
1019        """
1020        if arg:
1021            import shlex
1022            argv0 = sys.argv[0:1]
1023            sys.argv = shlex.split(arg)
1024            sys.argv[:0] = argv0
1025        # this is caught in the main debugger loop
1026        raise Restart
1027
1028    do_restart = do_run
1029
1030    def do_return(self, arg):
1031        """r(eturn)
1032        Continue execution until the current function returns.
1033        """
1034        self.set_return(self.curframe)
1035        return 1
1036    do_r = do_return
1037
1038    def do_continue(self, arg):
1039        """c(ont(inue))
1040        Continue execution, only stop when a breakpoint is encountered.
1041        """
1042        if not self.nosigint:
1043            try:
1044                Pdb._previous_sigint_handler = \
1045                    signal.signal(signal.SIGINT, self.sigint_handler)
1046            except ValueError:
1047                # ValueError happens when do_continue() is invoked from
1048                # a non-main thread in which case we just continue without
1049                # SIGINT set. Would printing a message here (once) make
1050                # sense?
1051                pass
1052        self.set_continue()
1053        return 1
1054    do_c = do_cont = do_continue
1055
1056    def do_jump(self, arg):
1057        """j(ump) lineno
1058        Set the next line that will be executed.  Only available in
1059        the bottom-most frame.  This lets you jump back and execute
1060        code again, or jump forward to skip code that you don't want
1061        to run.
1062
1063        It should be noted that not all jumps are allowed -- for
1064        instance it is not possible to jump into the middle of a
1065        for loop or out of a finally clause.
1066        """
1067        if self.curindex + 1 != len(self.stack):
1068            self.error('You can only jump within the bottom frame')
1069            return
1070        try:
1071            arg = int(arg)
1072        except ValueError:
1073            self.error("The 'jump' command requires a line number")
1074        else:
1075            try:
1076                # Do the jump, fix up our copy of the stack, and display the
1077                # new position
1078                self.curframe.f_lineno = arg
1079                self.stack[self.curindex] = self.stack[self.curindex][0], arg
1080                self.print_stack_entry(self.stack[self.curindex])
1081            except ValueError as e:
1082                self.error('Jump failed: %s' % e)
1083    do_j = do_jump
1084
1085    def do_debug(self, arg):
1086        """debug code
1087        Enter a recursive debugger that steps through the code
1088        argument (which is an arbitrary expression or statement to be
1089        executed in the current environment).
1090        """
1091        sys.settrace(None)
1092        globals = self.curframe.f_globals
1093        locals = self.curframe_locals
1094        p = Pdb(self.completekey, self.stdin, self.stdout)
1095        p.prompt = "(%s) " % self.prompt.strip()
1096        self.message("ENTERING RECURSIVE DEBUGGER")
1097        try:
1098            sys.call_tracing(p.run, (arg, globals, locals))
1099        except Exception:
1100            exc_info = sys.exc_info()[:2]
1101            self.error(traceback.format_exception_only(*exc_info)[-1].strip())
1102        self.message("LEAVING RECURSIVE DEBUGGER")
1103        sys.settrace(self.trace_dispatch)
1104        self.lastcmd = p.lastcmd
1105
1106    complete_debug = _complete_expression
1107
1108    def do_quit(self, arg):
1109        """q(uit)\nexit
1110        Quit from the debugger. The program being executed is aborted.
1111        """
1112        self._user_requested_quit = True
1113        self.set_quit()
1114        return 1
1115
1116    do_q = do_quit
1117    do_exit = do_quit
1118
1119    def do_EOF(self, arg):
1120        """EOF
1121        Handles the receipt of EOF as a command.
1122        """
1123        self.message('')
1124        self._user_requested_quit = True
1125        self.set_quit()
1126        return 1
1127
1128    def do_args(self, arg):
1129        """a(rgs)
1130        Print the argument list of the current function.
1131        """
1132        co = self.curframe.f_code
1133        dict = self.curframe_locals
1134        n = co.co_argcount + co.co_kwonlyargcount
1135        if co.co_flags & inspect.CO_VARARGS: n = n+1
1136        if co.co_flags & inspect.CO_VARKEYWORDS: n = n+1
1137        for i in range(n):
1138            name = co.co_varnames[i]
1139            if name in dict:
1140                self.message('%s = %r' % (name, dict[name]))
1141            else:
1142                self.message('%s = *** undefined ***' % (name,))
1143    do_a = do_args
1144
1145    def do_retval(self, arg):
1146        """retval
1147        Print the return value for the last return of a function.
1148        """
1149        if '__return__' in self.curframe_locals:
1150            self.message(repr(self.curframe_locals['__return__']))
1151        else:
1152            self.error('Not yet returned!')
1153    do_rv = do_retval
1154
1155    def _getval(self, arg):
1156        try:
1157            return eval(arg, self.curframe.f_globals, self.curframe_locals)
1158        except:
1159            exc_info = sys.exc_info()[:2]
1160            self.error(traceback.format_exception_only(*exc_info)[-1].strip())
1161            raise
1162
1163    def _getval_except(self, arg, frame=None):
1164        try:
1165            if frame is None:
1166                return eval(arg, self.curframe.f_globals, self.curframe_locals)
1167            else:
1168                return eval(arg, frame.f_globals, frame.f_locals)
1169        except:
1170            exc_info = sys.exc_info()[:2]
1171            err = traceback.format_exception_only(*exc_info)[-1].strip()
1172            return _rstr('** raised %s **' % err)
1173
1174    def do_p(self, arg):
1175        """p expression
1176        Print the value of the expression.
1177        """
1178        try:
1179            self.message(repr(self._getval(arg)))
1180        except:
1181            pass
1182
1183    def do_pp(self, arg):
1184        """pp expression
1185        Pretty-print the value of the expression.
1186        """
1187        try:
1188            self.message(pprint.pformat(self._getval(arg)))
1189        except:
1190            pass
1191
1192    complete_print = _complete_expression
1193    complete_p = _complete_expression
1194    complete_pp = _complete_expression
1195
1196    def do_list(self, arg):
1197        """l(ist) [first [,last] | .]
1198
1199        List source code for the current file.  Without arguments,
1200        list 11 lines around the current line or continue the previous
1201        listing.  With . as argument, list 11 lines around the current
1202        line.  With one argument, list 11 lines starting at that line.
1203        With two arguments, list the given range; if the second
1204        argument is less than the first, it is a count.
1205
1206        The current line in the current frame is indicated by "->".
1207        If an exception is being debugged, the line where the
1208        exception was originally raised or propagated is indicated by
1209        ">>", if it differs from the current line.
1210        """
1211        self.lastcmd = 'list'
1212        last = None
1213        if arg and arg != '.':
1214            try:
1215                if ',' in arg:
1216                    first, last = arg.split(',')
1217                    first = int(first.strip())
1218                    last = int(last.strip())
1219                    if last < first:
1220                        # assume it's a count
1221                        last = first + last
1222                else:
1223                    first = int(arg.strip())
1224                    first = max(1, first - 5)
1225            except ValueError:
1226                self.error('Error in argument: %r' % arg)
1227                return
1228        elif self.lineno is None or arg == '.':
1229            first = max(1, self.curframe.f_lineno - 5)
1230        else:
1231            first = self.lineno + 1
1232        if last is None:
1233            last = first + 10
1234        filename = self.curframe.f_code.co_filename
1235        breaklist = self.get_file_breaks(filename)
1236        try:
1237            lines = linecache.getlines(filename, self.curframe.f_globals)
1238            self._print_lines(lines[first-1:last], first, breaklist,
1239                              self.curframe)
1240            self.lineno = min(last, len(lines))
1241            if len(lines) < last:
1242                self.message('[EOF]')
1243        except KeyboardInterrupt:
1244            pass
1245    do_l = do_list
1246
1247    def do_longlist(self, arg):
1248        """longlist | ll
1249        List the whole source code for the current function or frame.
1250        """
1251        filename = self.curframe.f_code.co_filename
1252        breaklist = self.get_file_breaks(filename)
1253        try:
1254            lines, lineno = getsourcelines(self.curframe)
1255        except OSError as err:
1256            self.error(err)
1257            return
1258        self._print_lines(lines, lineno, breaklist, self.curframe)
1259    do_ll = do_longlist
1260
1261    def do_source(self, arg):
1262        """source expression
1263        Try to get source code for the given object and display it.
1264        """
1265        try:
1266            obj = self._getval(arg)
1267        except:
1268            return
1269        try:
1270            lines, lineno = getsourcelines(obj)
1271        except (OSError, TypeError) as err:
1272            self.error(err)
1273            return
1274        self._print_lines(lines, lineno)
1275
1276    complete_source = _complete_expression
1277
1278    def _print_lines(self, lines, start, breaks=(), frame=None):
1279        """Print a range of lines."""
1280        if frame:
1281            current_lineno = frame.f_lineno
1282            exc_lineno = self.tb_lineno.get(frame, -1)
1283        else:
1284            current_lineno = exc_lineno = -1
1285        for lineno, line in enumerate(lines, start):
1286            s = str(lineno).rjust(3)
1287            if len(s) < 4:
1288                s += ' '
1289            if lineno in breaks:
1290                s += 'B'
1291            else:
1292                s += ' '
1293            if lineno == current_lineno:
1294                s += '->'
1295            elif lineno == exc_lineno:
1296                s += '>>'
1297            self.message(s + '\t' + line.rstrip())
1298
1299    def do_whatis(self, arg):
1300        """whatis arg
1301        Print the type of the argument.
1302        """
1303        try:
1304            value = self._getval(arg)
1305        except:
1306            # _getval() already printed the error
1307            return
1308        code = None
1309        # Is it a function?
1310        try:
1311            code = value.__code__
1312        except Exception:
1313            pass
1314        if code:
1315            self.message('Function %s' % code.co_name)
1316            return
1317        # Is it an instance method?
1318        try:
1319            code = value.__func__.__code__
1320        except Exception:
1321            pass
1322        if code:
1323            self.message('Method %s' % code.co_name)
1324            return
1325        # Is it a class?
1326        if value.__class__ is type:
1327            self.message('Class %s.%s' % (value.__module__, value.__qualname__))
1328            return
1329        # None of the above...
1330        self.message(type(value))
1331
1332    complete_whatis = _complete_expression
1333
1334    def do_display(self, arg):
1335        """display [expression]
1336
1337        Display the value of the expression if it changed, each time execution
1338        stops in the current frame.
1339
1340        Without expression, list all display expressions for the current frame.
1341        """
1342        if not arg:
1343            self.message('Currently displaying:')
1344            for item in self.displaying.get(self.curframe, {}).items():
1345                self.message('%s: %r' % item)
1346        else:
1347            val = self._getval_except(arg)
1348            self.displaying.setdefault(self.curframe, {})[arg] = val
1349            self.message('display %s: %r' % (arg, val))
1350
1351    complete_display = _complete_expression
1352
1353    def do_undisplay(self, arg):
1354        """undisplay [expression]
1355
1356        Do not display the expression any more in the current frame.
1357
1358        Without expression, clear all display expressions for the current frame.
1359        """
1360        if arg:
1361            try:
1362                del self.displaying.get(self.curframe, {})[arg]
1363            except KeyError:
1364                self.error('not displaying %s' % arg)
1365        else:
1366            self.displaying.pop(self.curframe, None)
1367
1368    def complete_undisplay(self, text, line, begidx, endidx):
1369        return [e for e in self.displaying.get(self.curframe, {})
1370                if e.startswith(text)]
1371
1372    def do_interact(self, arg):
1373        """interact
1374
1375        Start an interactive interpreter whose global namespace
1376        contains all the (global and local) names found in the current scope.
1377        """
1378        ns = self.curframe.f_globals.copy()
1379        ns.update(self.curframe_locals)
1380        code.interact("*interactive*", local=ns)
1381
1382    def do_alias(self, arg):
1383        """alias [name [command [parameter parameter ...] ]]
1384        Create an alias called 'name' that executes 'command'.  The
1385        command must *not* be enclosed in quotes.  Replaceable
1386        parameters can be indicated by %1, %2, and so on, while %* is
1387        replaced by all the parameters.  If no command is given, the
1388        current alias for name is shown. If no name is given, all
1389        aliases are listed.
1390
1391        Aliases may be nested and can contain anything that can be
1392        legally typed at the pdb prompt.  Note!  You *can* override
1393        internal pdb commands with aliases!  Those internal commands
1394        are then hidden until the alias is removed.  Aliasing is
1395        recursively applied to the first word of the command line; all
1396        other words in the line are left alone.
1397
1398        As an example, here are two useful aliases (especially when
1399        placed in the .pdbrc file):
1400
1401        # Print instance variables (usage "pi classInst")
1402        alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])
1403        # Print instance variables in self
1404        alias ps pi self
1405        """
1406        args = arg.split()
1407        if len(args) == 0:
1408            keys = sorted(self.aliases.keys())
1409            for alias in keys:
1410                self.message("%s = %s" % (alias, self.aliases[alias]))
1411            return
1412        if args[0] in self.aliases and len(args) == 1:
1413            self.message("%s = %s" % (args[0], self.aliases[args[0]]))
1414        else:
1415            self.aliases[args[0]] = ' '.join(args[1:])
1416
1417    def do_unalias(self, arg):
1418        """unalias name
1419        Delete the specified alias.
1420        """
1421        args = arg.split()
1422        if len(args) == 0: return
1423        if args[0] in self.aliases:
1424            del self.aliases[args[0]]
1425
1426    def complete_unalias(self, text, line, begidx, endidx):
1427        return [a for a in self.aliases if a.startswith(text)]
1428
1429    # List of all the commands making the program resume execution.
1430    commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
1431                         'do_quit', 'do_jump']
1432
1433    # Print a traceback starting at the top stack frame.
1434    # The most recently entered frame is printed last;
1435    # this is different from dbx and gdb, but consistent with
1436    # the Python interpreter's stack trace.
1437    # It is also consistent with the up/down commands (which are
1438    # compatible with dbx and gdb: up moves towards 'main()'
1439    # and down moves towards the most recent stack frame).
1440
1441    def print_stack_trace(self):
1442        try:
1443            for frame_lineno in self.stack:
1444                self.print_stack_entry(frame_lineno)
1445        except KeyboardInterrupt:
1446            pass
1447
1448    def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
1449        frame, lineno = frame_lineno
1450        if frame is self.curframe:
1451            prefix = '> '
1452        else:
1453            prefix = '  '
1454        self.message(prefix +
1455                     self.format_stack_entry(frame_lineno, prompt_prefix))
1456
1457    # Provide help
1458
1459    def do_help(self, arg):
1460        """h(elp)
1461        Without argument, print the list of available commands.
1462        With a command name as argument, print help about that command.
1463        "help pdb" shows the full pdb documentation.
1464        "help exec" gives help on the ! command.
1465        """
1466        if not arg:
1467            return cmd.Cmd.do_help(self, arg)
1468        try:
1469            try:
1470                topic = getattr(self, 'help_' + arg)
1471                return topic()
1472            except AttributeError:
1473                command = getattr(self, 'do_' + arg)
1474        except AttributeError:
1475            self.error('No help for %r' % arg)
1476        else:
1477            if sys.flags.optimize >= 2:
1478                self.error('No help for %r; please do not run Python with -OO '
1479                           'if you need command help' % arg)
1480                return
1481            self.message(command.__doc__.rstrip())
1482
1483    do_h = do_help
1484
1485    def help_exec(self):
1486        """(!) statement
1487        Execute the (one-line) statement in the context of the current
1488        stack frame.  The exclamation point can be omitted unless the
1489        first word of the statement resembles a debugger command.  To
1490        assign to a global variable you must always prefix the command
1491        with a 'global' command, e.g.:
1492        (Pdb) global list_options; list_options = ['-l']
1493        (Pdb)
1494        """
1495        self.message((self.help_exec.__doc__ or '').strip())
1496
1497    def help_pdb(self):
1498        help()
1499
1500    # other helper functions
1501
1502    def lookupmodule(self, filename):
1503        """Helper function for break/clear parsing -- may be overridden.
1504
1505        lookupmodule() translates (possibly incomplete) file or module name
1506        into an absolute file name.
1507        """
1508        if os.path.isabs(filename) and  os.path.exists(filename):
1509            return filename
1510        f = os.path.join(sys.path[0], filename)
1511        if  os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1512            return f
1513        root, ext = os.path.splitext(filename)
1514        if ext == '':
1515            filename = filename + '.py'
1516        if os.path.isabs(filename):
1517            return filename
1518        for dirname in sys.path:
1519            while os.path.islink(dirname):
1520                dirname = os.readlink(dirname)
1521            fullname = os.path.join(dirname, filename)
1522            if os.path.exists(fullname):
1523                return fullname
1524        return None
1525
1526    def _runmodule(self, module_name):
1527        self._wait_for_mainpyfile = True
1528        self._user_requested_quit = False
1529        import runpy
1530        mod_name, mod_spec, code = runpy._get_module_details(module_name)
1531        self.mainpyfile = self.canonic(code.co_filename)
1532        import __main__
1533        __main__.__dict__.clear()
1534        __main__.__dict__.update({
1535            "__name__": "__main__",
1536            "__file__": self.mainpyfile,
1537            "__package__": mod_spec.parent,
1538            "__loader__": mod_spec.loader,
1539            "__spec__": mod_spec,
1540            "__builtins__": __builtins__,
1541        })
1542        self.run(code)
1543
1544    def _runscript(self, filename):
1545        # The script has to run in __main__ namespace (or imports from
1546        # __main__ will break).
1547        #
1548        # So we clear up the __main__ and set several special variables
1549        # (this gets rid of pdb's globals and cleans old variables on restarts).
1550        import __main__
1551        __main__.__dict__.clear()
1552        __main__.__dict__.update({"__name__"    : "__main__",
1553                                  "__file__"    : filename,
1554                                  "__builtins__": __builtins__,
1555                                 })
1556
1557        # When bdb sets tracing, a number of call and line events happens
1558        # BEFORE debugger even reaches user's code (and the exact sequence of
1559        # events depends on python version). So we take special measures to
1560        # avoid stopping before we reach the main script (see user_line and
1561        # user_call for details).
1562        self._wait_for_mainpyfile = True
1563        self.mainpyfile = self.canonic(filename)
1564        self._user_requested_quit = False
1565        with open(filename, "rb") as fp:
1566            statement = "exec(compile(%r, %r, 'exec'))" % \
1567                        (fp.read(), self.mainpyfile)
1568        self.run(statement)
1569
1570# Collect all command help into docstring, if not run with -OO
1571
1572if __doc__ is not None:
1573    # unfortunately we can't guess this order from the class definition
1574    _help_order = [
1575        'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable',
1576        'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until',
1577        'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist',
1578        'args', 'p', 'pp', 'whatis', 'source', 'display', 'undisplay',
1579        'interact', 'alias', 'unalias', 'debug', 'quit',
1580    ]
1581
1582    for _command in _help_order:
1583        __doc__ += getattr(Pdb, 'do_' + _command).__doc__.strip() + '\n\n'
1584    __doc__ += Pdb.help_exec.__doc__
1585
1586    del _help_order, _command
1587
1588
1589# Simplified interface
1590
1591def run(statement, globals=None, locals=None):
1592    Pdb().run(statement, globals, locals)
1593
1594def runeval(expression, globals=None, locals=None):
1595    return Pdb().runeval(expression, globals, locals)
1596
1597def runctx(statement, globals, locals):
1598    # B/W compatibility
1599    run(statement, globals, locals)
1600
1601def runcall(*args, **kwds):
1602    return Pdb().runcall(*args, **kwds)
1603
1604def set_trace(*, header=None):
1605    pdb = Pdb()
1606    if header is not None:
1607        pdb.message(header)
1608    pdb.set_trace(sys._getframe().f_back)
1609
1610# Post-Mortem interface
1611
1612def post_mortem(t=None):
1613    # handling the default
1614    if t is None:
1615        # sys.exc_info() returns (type, value, traceback) if an exception is
1616        # being handled, otherwise it returns None
1617        t = sys.exc_info()[2]
1618    if t is None:
1619        raise ValueError("A valid traceback must be passed if no "
1620                         "exception is being handled")
1621
1622    p = Pdb()
1623    p.reset()
1624    p.interaction(None, t)
1625
1626def pm():
1627    post_mortem(sys.last_traceback)
1628
1629
1630# Main program for testing
1631
1632TESTCMD = 'import x; x.main()'
1633
1634def test():
1635    run(TESTCMD)
1636
1637# print help
1638def help():
1639    import pydoc
1640    pydoc.pager(__doc__)
1641
1642_usage = """\
1643usage: pdb.py [-c command] ... [-m module | pyfile] [arg] ...
1644
1645Debug the Python program given by pyfile. Alternatively,
1646an executable module or package to debug can be specified using
1647the -m switch.
1648
1649Initial commands are read from .pdbrc files in your home directory
1650and in the current directory, if they exist.  Commands supplied with
1651-c are executed after commands from .pdbrc files.
1652
1653To let the script run until an exception occurs, use "-c continue".
1654To let the script run up to a given line X in the debugged file, use
1655"-c 'until X'"."""
1656
1657def main():
1658    import getopt
1659
1660    opts, args = getopt.getopt(sys.argv[1:], 'mhc:', ['help', 'command='])
1661
1662    if not args:
1663        print(_usage)
1664        sys.exit(2)
1665
1666    commands = []
1667    run_as_module = False
1668    for opt, optarg in opts:
1669        if opt in ['-h', '--help']:
1670            print(_usage)
1671            sys.exit()
1672        elif opt in ['-c', '--command']:
1673            commands.append(optarg)
1674        elif opt in ['-m']:
1675            run_as_module = True
1676
1677    mainpyfile = args[0]     # Get script filename
1678    if not run_as_module and not os.path.exists(mainpyfile):
1679        print('Error:', mainpyfile, 'does not exist')
1680        sys.exit(1)
1681
1682    sys.argv[:] = args      # Hide "pdb.py" and pdb options from argument list
1683
1684    # Replace pdb's dir with script's dir in front of module search path.
1685    if not run_as_module:
1686        sys.path[0] = os.path.dirname(mainpyfile)
1687
1688    # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1689    # modified by the script being debugged. It's a bad idea when it was
1690    # changed by the user from the command line. There is a "restart" command
1691    # which allows explicit specification of command line arguments.
1692    pdb = Pdb()
1693    pdb.rcLines.extend(commands)
1694    while True:
1695        try:
1696            if run_as_module:
1697                pdb._runmodule(mainpyfile)
1698            else:
1699                pdb._runscript(mainpyfile)
1700            if pdb._user_requested_quit:
1701                break
1702            print("The program finished and will be restarted")
1703        except Restart:
1704            print("Restarting", mainpyfile, "with arguments:")
1705            print("\t" + " ".join(args))
1706        except SystemExit:
1707            # In most cases SystemExit does not warrant a post-mortem session.
1708            print("The program exited via sys.exit(). Exit status:", end=' ')
1709            print(sys.exc_info()[1])
1710        except SyntaxError:
1711            traceback.print_exc()
1712            sys.exit(1)
1713        except:
1714            traceback.print_exc()
1715            print("Uncaught exception. Entering post mortem debugging")
1716            print("Running 'cont' or 'step' will restart the program")
1717            t = sys.exc_info()[2]
1718            pdb.interaction(None, t)
1719            print("Post mortem debugger finished. The " + mainpyfile +
1720                  " will be restarted")
1721
1722
1723# When invoked as main program, invoke the debugger on a script
1724if __name__ == '__main__':
1725    import pdb
1726    pdb.main()
1727