ยปCore Development>Code coverage>Lib/pdb.py

Python code coverage for Lib/pdb.py

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