~ubuntu-branches/ubuntu/trusty/python3.4/trusty-proposed

« back to all changes in this revision

Viewing changes to Lib/pdb.py

  • Committer: Package Import Robot
  • Author(s): Matthias Klose
  • Date: 2013-11-25 09:44:27 UTC
  • Revision ID: package-import@ubuntu.com-20131125094427-lzxj8ap5w01lmo7f
Tags: upstream-3.4~b1
ImportĀ upstreamĀ versionĀ 3.4~b1

Show diffs side-by-side

added added

removed removed

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