blob: c16cde6bd7460a0a34dfb02e80f43fb1b6abb7ef [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#! /usr/bin/env python3
Guido van Rossumf17361d1996-07-30 16:28:13 +00002
Georg Brandl02053ee2010-07-18 10:11:03 +00003"""
4The Python Debugger Pdb
5=======================
Guido van Rossum92df0c61992-01-14 18:30:15 +00006
Georg Brandl02053ee2010-07-18 10:11:03 +00007To use the debugger in its simplest form:
8
9 >>> import pdb
10 >>> pdb.run('<a statement>')
11
12The debugger's prompt is '(Pdb) '. This will stop in the first
13function call in <a statement>.
14
15Alternatively, if a statement terminated with an unhandled exception,
16you can use pdb's post-mortem facility to inspect the contents of the
17traceback:
18
19 >>> <a statement>
20 <exception traceback>
21 >>> import pdb
22 >>> pdb.pm()
23
24The commands recognized by the debugger are listed in the next
25section. Most can be abbreviated as indicated; e.g., h(elp) means
26that 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel',
27nor as 'H' or 'Help' or 'HELP'). Optional arguments are enclosed in
28square brackets. Alternatives in the command syntax are separated
29by a vertical bar (|).
30
31A blank line repeats the previous command literally, except for
32'list', where it lists the next 11 lines.
33
34Commands that the debugger doesn't recognize are assumed to be Python
35statements and are executed in the context of the program being
36debugged. Python statements can also be prefixed with an exclamation
37point ('!'). This is a powerful way to inspect the program being
38debugged; it is even possible to change variables or call functions.
39When an exception occurs in such a statement, the exception name is
40printed but the debugger's state is not changed.
41
42The debugger supports aliases, which can save typing. And aliases can
43have parameters (see the alias help entry) which allows one a certain
44level of adaptability to the context under examination.
45
46Multiple commands may be entered on a single line, separated by the
47pair ';;'. No intelligence is applied to separating the commands; the
48input is split at the first ';;', even if it is in the middle of a
49quoted string.
50
51If a file ".pdbrc" exists in your home directory or in the current
52directory, it is read in and executed as if it had been typed at the
53debugger prompt. This is particularly useful for aliases. If both
54files exist, the one in the home directory is read first and aliases
55defined there can be overriden by the local file.
56
57Aside from aliases, the debugger is not directly programmable; but it
58is implemented as a class from which you can derive your own debugger
59class, which you can make as fancy as you like.
60
61
62Debugger commands
63=================
64
65h(elp)
66 Without argument, print the list of available commands. With
67 a command name as argument, print help about that command.
68
69w(here)
70 Print a stack trace, with the most recent frame at the bottom.
71 An arrow indicates the "current frame", which determines the
72 context of most commands.
73
74d(own) [ count ]
75 Move the current frame count (default one) levels down in the
76 stack trace (to a newer frame).
77
78u(p) [ count ]
79 Move the current frame count (default one) levels up in the
80 stack trace (to an older frame).
81
82b(reak) [ ([filename:]lineno | function) [, condition] ]
83 With a filename:lineno argument, set a break there. If
84 filename is omitted, use the current file. With a function
85 name, set a break at the first executable line of that
86 function. Without argument, list all breaks. Each breakpoint
87 is assigned a number to which all the other breakpoint
88 commands refer.
89
90 The condition argument, if present, is a string which must
91 evaluate to true in order for the breakpoint to be honored.
92
93tbreak [ ([filename:]lineno | function) [, condition] ]
94 Temporary breakpoint, which is removed automatically when it
95 is first hit. The arguments are the same as for break.
96
97cl(ear) [bpnumber [bpnumber ...] ]
98 With a space separated list of breakpoint numbers, clear those
99 breakpoints. Without argument, clear all breaks (but first
100 ask confirmation).
101
102disable bpnumber [bpnumber ...]
103 Disable the breakpoints given as a space separated list of
104 breakpoint numbers. Disabling a breakpoint means it cannot
105 cause the program to stop execution, but unlike clearing a
106 breakpoint, it remains in the list of breakpoints and can be
107 (re-)enabled.
108
109enable bpnumber [bpnumber ...]
110 Enable the breakpoints specified.
111
112ignore bpnumber [count]
113 Set the ignore count for the given breakpoint number. If
114 count is omitted, the ignore count is set to 0. A breakpoint
115 becomes active when the ignore count is zero. When non-zero,
116 the count is decremented each time the breakpoint is reached
117 and the breakpoint is not disabled and any associated
118 condition evaluates to true.
119
120condition bpnumber [condition]
121 Set a new condition for the breakpoint, an expression which
122 must evaluate to true before the breakpoint is honored. If
123 condition is absent, any existing condition is removed; i.e.,
124 the breakpoint is made unconditional.
125
126commands [bpnumber]
127 Specify a list of commands for the breakpoint. Type a line
128 containing just 'end' to terminate the commands. The commands
129 are executed when the breakpoint is hit.
130
131 With no breakpoint number argument, refers to the last
132 breakpoint set.
133
134s(tep)
135 Execute the current line, stop at the first possible occasion
136 (either in a function that is called or in the current
137 function).
138
139n(ext)
140 Continue execution until the next line in the current function
141 is reached or it returns.
142
143unt(il)
144 Continue execution until the line with a number greater than
145 the current one is reached or until the current frame returns.
146
147r(eturn)
148 Continue execution until the current function returns.
149
150run [args...]
151 Restart the debugged python program. If a string is supplied
152 it is splitted with "shlex", and the result is used as the new
153 sys.argv. History, breakpoints, actions and debugger options
154 are preserved. "restart" is an alias for "run".
155
156c(ont(inue))
157 Continue execution, only stop when a breakpoint is encountered.
158
159l(ist) [first [,last]]
160 List source code for the current file.
161 Without arguments, list 11 lines around the current line
162 or continue the previous listing.
Georg Brandla91a94b2010-07-30 07:14:01 +0000163 With . as argument, list 11 lines around the current line.
Georg Brandl02053ee2010-07-18 10:11:03 +0000164 With one argument, list 11 lines starting at that line.
165 With two arguments, list the given range;
166 if the second argument is less than the first, it is a count.
167
168a(rgs)
169 Print the argument list of the current function.
170
171p expression
172 Print the value of the expression.
173
174(!) statement
175 Execute the (one-line) statement in the context of the current
176 stack frame. The exclamation point can be omitted unless the
177 first word of the statement resembles a debugger command. To
178 assign to a global variable you must always prefix the command
179 with a 'global' command, e.g.:
180 (Pdb) global list_options; list_options = ['-l']
181 (Pdb)
182
183
184whatis arg
185 Print the type of the argument.
186
187alias [name [command]]
188 Creates an alias called 'name' that executes 'command'. The
189 command must *not* be enclosed in quotes. Replaceable
190 parameters can be indicated by %1, %2, and so on, while %* is
191 replaced by all the parameters. If no command is given, the
192 current alias for name is shown. If no name is given, all
193 aliases are listed.
194
195 Aliases may be nested and can contain anything that can be
196 legally typed at the pdb prompt. Note! You *can* override
197 internal pdb commands with aliases! Those internal commands
198 are then hidden until the alias is removed. Aliasing is
199 recursively applied to the first word of the command line; all
200 other words in the line are left alone.
201
202 As an example, here are two useful aliases (especially when
203 placed in the .pdbrc file):
204
205 # Print instance variables (usage "pi classInst")
206 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
207 # Print instance variables in self
208 alias ps pi self
209
210unalias name
211 Delete the specified alias.
212
213q(uit)
214 Quit from the debugger. The program being executed is aborted.
215"""
Guido van Rossum921c8241992-01-10 14:54:42 +0000216
Guido van Rossum921c8241992-01-10 14:54:42 +0000217import sys
218import linecache
Guido van Rossum23efba41992-01-27 16:58:47 +0000219import cmd
220import bdb
Alexandre Vassalotti1f2ba4b2008-05-16 07:12:44 +0000221from reprlib import Repr
Guido van Rossumb5699c71998-07-20 23:13:54 +0000222import os
Barry Warsaw2bee8fe1999-09-09 16:32:41 +0000223import re
Barry Warsaw210bd202002-11-05 22:40:20 +0000224import pprint
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000225import traceback
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226
227
228class Restart(Exception):
229 """Causes a debugger to be restarted for the debugged python program."""
230 pass
231
Guido van Rossumef1b41b2002-09-10 21:57:14 +0000232# Create a custom safe Repr instance and increase its maxstring.
233# The default of 30 truncates error messages too easily.
234_repr = Repr()
235_repr.maxstring = 200
236_saferepr = _repr.repr
237
Skip Montanaro352674d2001-02-07 23:14:30 +0000238__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
239 "post_mortem", "help"]
240
Barry Warsaw2bee8fe1999-09-09 16:32:41 +0000241def find_function(funcname, filename):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000242 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
Tim Peters2344fae2001-01-15 00:50:52 +0000243 try:
244 fp = open(filename)
245 except IOError:
246 return None
247 # consumer of this info expects the first line to be 1
248 lineno = 1
249 answer = None
250 while 1:
251 line = fp.readline()
252 if line == '':
253 break
254 if cre.match(line):
255 answer = funcname, filename, lineno
256 break
257 lineno = lineno + 1
258 fp.close()
259 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +0000260
261
Guido van Rossuma558e371994-11-10 22:27:35 +0000262# Interaction prompt line will separate file and call info from code
263# text using value of line_prefix string. A newline and arrow may
264# be to your liking. You can set it once pdb is imported using the
265# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +0000266# line_prefix = ': ' # Use this to get the old situation back
267line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +0000268
Guido van Rossum23efba41992-01-27 16:58:47 +0000269class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +0000270
Georg Brandl243ad662009-05-05 09:00:19 +0000271 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None):
272 bdb.Bdb.__init__(self, skip=skip)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000273 cmd.Cmd.__init__(self, completekey, stdin, stdout)
274 if stdout:
275 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000276 self.prompt = '(Pdb) '
277 self.aliases = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000278 self.mainpyfile = ''
279 self._wait_for_mainpyfile = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000280 # Try to load readline if it exists
281 try:
282 import readline
283 except ImportError:
284 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000285
Tim Peters2344fae2001-01-15 00:50:52 +0000286 # Read $HOME/.pdbrc and ./.pdbrc
287 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +0000288 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +0000289 envHome = os.environ['HOME']
290 try:
291 rcFile = open(os.path.join(envHome, ".pdbrc"))
292 except IOError:
293 pass
294 else:
295 for line in rcFile.readlines():
296 self.rcLines.append(line)
297 rcFile.close()
298 try:
299 rcFile = open(".pdbrc")
300 except IOError:
301 pass
302 else:
303 for line in rcFile.readlines():
304 self.rcLines.append(line)
305 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +0000306
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000307 self.commands = {} # associates a command list to breakpoint numbers
Benjamin Petersond23f8222009-04-05 19:13:16 +0000308 self.commands_doprompt = {} # for each bp num, tells if the prompt
309 # must be disp. after execing the cmd list
310 self.commands_silent = {} # for each bp num, tells if the stack trace
311 # must be disp. after execing the cmd list
312 self.commands_defining = False # True while in the process of defining
313 # a command list
314 self.commands_bnum = None # The breakpoint number for which we are
315 # defining a list
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000316
Tim Peters2344fae2001-01-15 00:50:52 +0000317 def reset(self):
318 bdb.Bdb.reset(self)
319 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000320
Tim Peters2344fae2001-01-15 00:50:52 +0000321 def forget(self):
322 self.lineno = None
323 self.stack = []
324 self.curindex = 0
325 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +0000326
Tim Peters2344fae2001-01-15 00:50:52 +0000327 def setup(self, f, t):
328 self.forget()
329 self.stack, self.curindex = self.get_stack(f, t)
330 self.curframe = self.stack[self.curindex][0]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000331 # The f_locals dictionary is updated from the actual frame
332 # locals whenever the .f_locals accessor is called, so we
333 # cache it here to ensure that modifications are not overwritten.
334 self.curframe_locals = self.curframe.f_locals
Georg Brandle0230912010-07-30 08:29:39 +0000335 return self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000336
Tim Peters2344fae2001-01-15 00:50:52 +0000337 # Can be executed earlier than 'setup' if desired
338 def execRcLines(self):
Georg Brandle0230912010-07-30 08:29:39 +0000339 if not self.rcLines:
340 return
341 # local copy because of recursion
342 rcLines = self.rcLines
343 rcLines.reverse()
344 # execute every line only once
345 self.rcLines = []
346 while rcLines:
347 line = rcLines.pop().strip()
348 if line and line[0] != '#':
349 if self.onecmd(line):
350 # if onecmd returns True, the command wants to exit
351 # from the interaction, save leftover rc lines
352 # to execute before next interaction
353 self.rcLines += reversed(rcLines)
354 return True
Guido van Rossum2424f851998-09-11 22:50:09 +0000355
Tim Peters280488b2002-08-23 18:19:30 +0000356 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000357
358 def user_call(self, frame, argument_list):
359 """This method is called when there is the remote possibility
360 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000361 if self._wait_for_mainpyfile:
362 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000363 if self.stop_here(frame):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000364 print('--Call--', file=self.stdout)
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000365 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000366
Tim Peters2344fae2001-01-15 00:50:52 +0000367 def user_line(self, frame):
368 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000369 if self._wait_for_mainpyfile:
370 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
371 or frame.f_lineno<= 0):
372 return
373 self._wait_for_mainpyfile = 0
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000374 if self.bp_commands(frame):
375 self.interaction(frame, None)
376
Georg Brandle0230912010-07-30 08:29:39 +0000377 def bp_commands(self, frame):
Georg Brandl3078df02009-05-05 09:11:31 +0000378 """Call every command that was set for the current active breakpoint
379 (if there is one).
380
381 Returns True if the normal interaction function must be called,
382 False otherwise."""
383 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
384 if getattr(self, "currentbp", False) and \
385 self.currentbp in self.commands:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000386 currentbp = self.currentbp
387 self.currentbp = 0
388 lastcmd_back = self.lastcmd
389 self.setup(frame, None)
390 for line in self.commands[currentbp]:
391 self.onecmd(line)
392 self.lastcmd = lastcmd_back
393 if not self.commands_silent[currentbp]:
394 self.print_stack_entry(self.stack[self.curindex])
395 if self.commands_doprompt[currentbp]:
396 self.cmdloop()
397 self.forget()
398 return
399 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000400
Tim Peters2344fae2001-01-15 00:50:52 +0000401 def user_return(self, frame, return_value):
402 """This function is called when a return trap is set here."""
403 frame.f_locals['__return__'] = return_value
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000404 print('--Return--', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000405 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000406
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000407 def user_exception(self, frame, exc_info):
Tim Peters2344fae2001-01-15 00:50:52 +0000408 """This function is called if an exception occurs,
409 but only if we are to stop at or just below this level."""
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000410 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000411 frame.f_locals['__exception__'] = exc_type, exc_value
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000412 exc_type_name = exc_type.__name__
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000413 print(exc_type_name + ':', _saferepr(exc_value), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000414 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000415
Tim Peters2344fae2001-01-15 00:50:52 +0000416 # General interaction function
417
418 def interaction(self, frame, traceback):
Georg Brandle0230912010-07-30 08:29:39 +0000419 if self.setup(frame, traceback):
420 # no interaction desired at this time (happens if .pdbrc contains
421 # a command like "continue")
422 self.forget()
423 return
Tim Peters2344fae2001-01-15 00:50:52 +0000424 self.print_stack_entry(self.stack[self.curindex])
425 self.cmdloop()
426 self.forget()
427
Benjamin Petersond23f8222009-04-05 19:13:16 +0000428 def displayhook(self, obj):
429 """Custom displayhook for the exec in default(), which prevents
430 assignment of the _ variable in the builtins.
431 """
Georg Brandl9fa2e022009-09-16 16:40:45 +0000432 # reproduce the behavior of the standard displayhook, not printing None
433 if obj is not None:
434 print(repr(obj))
Benjamin Petersond23f8222009-04-05 19:13:16 +0000435
Tim Peters2344fae2001-01-15 00:50:52 +0000436 def default(self, line):
437 if line[:1] == '!': line = line[1:]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000438 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000439 globals = self.curframe.f_globals
440 try:
441 code = compile(line + '\n', '<stdin>', 'single')
Christian Heimes679db4a2008-01-18 09:56:22 +0000442 save_stdout = sys.stdout
443 save_stdin = sys.stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000444 save_displayhook = sys.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000445 try:
446 sys.stdin = self.stdin
447 sys.stdout = self.stdout
Benjamin Petersond23f8222009-04-05 19:13:16 +0000448 sys.displayhook = self.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000449 exec(code, globals, locals)
450 finally:
451 sys.stdout = save_stdout
452 sys.stdin = save_stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000453 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000454 except:
455 t, v = sys.exc_info()[:2]
456 if type(t) == type(''):
457 exc_type_name = t
458 else: exc_type_name = t.__name__
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000459 print('***', exc_type_name + ':', v, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000460
461 def precmd(self, line):
462 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000463 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000464 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000465 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000466 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000467 line = self.aliases[args[0]]
468 ii = 1
469 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000470 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000471 tmpArg)
472 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000473 line = line.replace("%*", ' '.join(args[1:]))
474 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000475 # split into ';;' separated commands
476 # unless it's an alias command
477 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000478 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000479 if marker >= 0:
480 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000481 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000482 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000483 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000484 return line
485
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000486 def onecmd(self, line):
487 """Interpret the argument as though it had been typed in response
488 to the prompt.
489
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000490 Checks whether this line is typed at the normal prompt or in
491 a breakpoint command list definition.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000492 """
493 if not self.commands_defining:
494 return cmd.Cmd.onecmd(self, line)
495 else:
496 return self.handle_command_def(line)
497
498 def handle_command_def(self,line):
499 """ Handles one command line during command list definition. """
500 cmd, arg, line = self.parseline(line)
501 if cmd == 'silent':
502 self.commands_silent[self.commands_bnum] = True
503 return # continue to handle other cmd def in the cmd list
504 elif cmd == 'end':
505 self.cmdqueue = []
506 return 1 # end of cmd list
507 cmdlist = self.commands[self.commands_bnum]
508 if (arg):
509 cmdlist.append(cmd+' '+arg)
510 else:
511 cmdlist.append(cmd)
512 # Determine if we must stop
513 try:
514 func = getattr(self, 'do_' + cmd)
515 except AttributeError:
516 func = self.default
Georg Brandl3078df02009-05-05 09:11:31 +0000517 # one of the resuming commands
518 if func.__name__ in self.commands_resuming:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000519 self.commands_doprompt[self.commands_bnum] = False
520 self.cmdqueue = []
521 return 1
522 return
523
Tim Peters2344fae2001-01-15 00:50:52 +0000524 # Command definitions, called by cmdloop()
525 # The argument is the remaining string on the command line
526 # Return true to exit from the command loop
527
528 do_h = cmd.Cmd.do_help
529
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000530 def do_commands(self, arg):
Georg Brandl3078df02009-05-05 09:11:31 +0000531 """Defines a list of commands associated to a breakpoint.
532
533 Those commands will be executed whenever the breakpoint causes
534 the program to stop execution."""
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000535 if not arg:
536 bnum = len(bdb.Breakpoint.bpbynumber)-1
537 else:
538 try:
539 bnum = int(arg)
540 except:
Georg Brandl3078df02009-05-05 09:11:31 +0000541 print("Usage : commands [bnum]\n ...\n end",
542 file=self.stdout)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000543 return
544 self.commands_bnum = bnum
545 self.commands[bnum] = []
546 self.commands_doprompt[bnum] = True
547 self.commands_silent[bnum] = False
548 prompt_back = self.prompt
549 self.prompt = '(com) '
550 self.commands_defining = True
551 self.cmdloop()
552 self.commands_defining = False
553 self.prompt = prompt_back
554
Tim Peters2344fae2001-01-15 00:50:52 +0000555 def do_break(self, arg, temporary = 0):
556 # break [ ([filename:]lineno | function) [, "condition"] ]
557 if not arg:
558 if self.breaks: # There's at least one
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000559 print("Num Type Disp Enb Where", file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000560 for bp in bdb.Breakpoint.bpbynumber:
561 if bp:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000562 bp.bpprint(self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000563 return
564 # parse arguments; comma has lowest precedence
565 # and cannot occur in filename
566 filename = None
567 lineno = None
568 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000569 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000570 if comma > 0:
571 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000572 cond = arg[comma+1:].lstrip()
573 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000574 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000575 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000576 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000577 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000578 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000579 f = self.lookupmodule(filename)
580 if not f:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000581 print('*** ', repr(filename), end=' ', file=self.stdout)
582 print('not found from sys.path', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000583 return
584 else:
585 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000586 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000587 try:
588 lineno = int(arg)
Guido van Rossumb940e112007-01-10 16:19:56 +0000589 except ValueError as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000590 print('*** Bad lineno:', arg, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000591 return
592 else:
593 # no colon; can be lineno or function
594 try:
595 lineno = int(arg)
596 except ValueError:
597 try:
598 func = eval(arg,
599 self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +0000600 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000601 except:
602 func = arg
603 try:
Christian Heimesff737952007-11-27 10:40:20 +0000604 if hasattr(func, '__func__'):
605 func = func.__func__
Neal Norwitz221085d2007-02-25 20:55:47 +0000606 code = func.__code__
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000607 #use co_name to identify the bkpt (function names
608 #could be aliased, but co_name is invariant)
609 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000610 lineno = code.co_firstlineno
611 filename = code.co_filename
612 except:
613 # last thing to try
614 (ok, filename, ln) = self.lineinfo(arg)
615 if not ok:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000616 print('*** The specified object', end=' ', file=self.stdout)
617 print(repr(arg), end=' ', file=self.stdout)
618 print('is not a function', file=self.stdout)
619 print('or was not found along sys.path.', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000620 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000621 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000622 lineno = int(ln)
623 if not filename:
624 filename = self.defaultFile()
625 # Check for reasonable breakpoint
626 line = self.checkline(filename, lineno)
627 if line:
628 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000629 err = self.set_break(filename, line, temporary, cond, funcname)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000630 if err: print('***', err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000631 else:
632 bp = self.get_breaks(filename, line)[-1]
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000633 print("Breakpoint %d at %s:%d" % (bp.number,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000634 bp.file,
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000635 bp.line), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000636
637 # To be overridden in derived debuggers
638 def defaultFile(self):
639 """Produce a reasonable default."""
640 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000641 if filename == '<string>' and self.mainpyfile:
642 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000643 return filename
644
645 do_b = do_break
646
647 def do_tbreak(self, arg):
648 self.do_break(arg, 1)
649
650 def lineinfo(self, identifier):
651 failed = (None, None, None)
652 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000653 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000654 if len(idstring) == 1:
655 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000656 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000657 elif len(idstring) == 3:
658 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000659 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000660 else:
661 return failed
662 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000663 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000664 # Protection for derived debuggers
665 if parts[0] == 'self':
666 del parts[0]
667 if len(parts) == 0:
668 return failed
669 # Best first guess at file to look at
670 fname = self.defaultFile()
671 if len(parts) == 1:
672 item = parts[0]
673 else:
674 # More than one part.
675 # First is module, second is method/class
676 f = self.lookupmodule(parts[0])
677 if f:
678 fname = f
679 item = parts[1]
680 answer = find_function(item, fname)
681 return answer or failed
682
683 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000684 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000685
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000686 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
687 line or EOF). Warning: testing is not comprehensive.
688 """
Georg Brandl1e30bd32010-07-30 07:21:26 +0000689 # this method should be callable before starting debugging, so default
690 # to "no globals" if there is no current frame
691 globs = self.curframe.f_globals if hasattr(self, 'curframe') else None
692 line = linecache.getline(filename, lineno, globs)
Tim Peters2344fae2001-01-15 00:50:52 +0000693 if not line:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000694 print('End of file', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000695 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000696 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000697 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000698 if (not line or (line[0] == '#') or
699 (line[:3] == '"""') or line[:3] == "'''"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000700 print('*** Blank or comment', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000701 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000702 return lineno
703
704 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000705 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000706 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000707 try:
708 i = int(i)
709 except ValueError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000710 print('Breakpoint index %r is not a number' % i, file=self.stdout)
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000711 continue
712
713 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000714 print('No breakpoint numbered', i, file=self.stdout)
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000715 continue
716
717 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000718 if bp:
719 bp.enable()
720
721 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000722 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000723 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000724 try:
725 i = int(i)
726 except ValueError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000727 print('Breakpoint index %r is not a number' % i, file=self.stdout)
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000728 continue
Tim Petersf545baa2003-06-15 23:26:30 +0000729
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000730 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000731 print('No breakpoint numbered', i, file=self.stdout)
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000732 continue
733
734 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000735 if bp:
736 bp.disable()
737
738 def do_condition(self, arg):
739 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000740 args = arg.split(' ', 1)
Thomas Woutersb2137042007-02-01 18:02:27 +0000741 try:
742 bpnum = int(args[0].strip())
743 except ValueError:
744 # something went wrong
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000745 print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000746 return
Tim Peters2344fae2001-01-15 00:50:52 +0000747 try:
748 cond = args[1]
749 except:
750 cond = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000751 try:
752 bp = bdb.Breakpoint.bpbynumber[bpnum]
753 except IndexError:
Neal Norwitz752abd02008-05-13 04:55:24 +0000754 print('Breakpoint index %r is not valid' % args[0],
755 file=self.stdout)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000756 return
Tim Peters2344fae2001-01-15 00:50:52 +0000757 if bp:
758 bp.cond = cond
759 if not cond:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000760 print('Breakpoint', bpnum, end=' ', file=self.stdout)
761 print('is now unconditional.', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000762
763 def do_ignore(self,arg):
764 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000765 args = arg.split()
Thomas Woutersb2137042007-02-01 18:02:27 +0000766 try:
767 bpnum = int(args[0].strip())
768 except ValueError:
769 # something went wrong
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000770 print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000771 return
Tim Peters2344fae2001-01-15 00:50:52 +0000772 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000773 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000774 except:
775 count = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +0000776 try:
777 bp = bdb.Breakpoint.bpbynumber[bpnum]
778 except IndexError:
Neal Norwitz752abd02008-05-13 04:55:24 +0000779 print('Breakpoint index %r is not valid' % args[0],
780 file=self.stdout)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000781 return
Tim Peters2344fae2001-01-15 00:50:52 +0000782 if bp:
783 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000784 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000785 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000786 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000787 reply = reply + '%d crossings' % count
788 else:
789 reply = reply + '1 crossing'
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000790 print(reply + ' of breakpoint %d.' % bpnum, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000791 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000792 print('Will stop next time breakpoint', end=' ', file=self.stdout)
793 print(bpnum, 'is reached.', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000794
795 def do_clear(self, arg):
796 """Three possibilities, tried in this order:
797 clear -> clear all breaks, ask for confirmation
798 clear file:lineno -> clear all breaks at file:lineno
799 clear bpno bpno ... -> clear breakpoints by number"""
800 if not arg:
801 try:
Guido van Rossumc5b6ab02007-05-27 09:19:52 +0000802 reply = input('Clear all breaks? ')
Tim Peters2344fae2001-01-15 00:50:52 +0000803 except EOFError:
804 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000805 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000806 if reply in ('y', 'yes'):
807 self.clear_all_breaks()
808 return
809 if ':' in arg:
810 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000811 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000812 filename = arg[:i]
813 arg = arg[i+1:]
814 try:
815 lineno = int(arg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000816 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000817 err = "Invalid line number (%s)" % arg
818 else:
819 err = self.clear_break(filename, lineno)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000820 if err: print('***', err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000821 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000822 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000823 for i in numberlist:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000824 try:
825 i = int(i)
826 except ValueError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000827 print('Breakpoint index %r is not a number' % i, file=self.stdout)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000828 continue
829
Georg Brandl6d2b3462005-08-24 07:36:17 +0000830 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000831 print('No breakpoint numbered', i, file=self.stdout)
Georg Brandl6d2b3462005-08-24 07:36:17 +0000832 continue
Tim Peters2344fae2001-01-15 00:50:52 +0000833 err = self.clear_bpbynumber(i)
834 if err:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000835 print('***', err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000836 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000837 print('Deleted breakpoint', i, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000838 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
839
840 def do_where(self, arg):
841 self.print_stack_trace()
842 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000843 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000844
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000845 def _select_frame(self, number):
846 assert 0 <= number < len(self.stack)
847 self.curindex = number
848 self.curframe = self.stack[self.curindex][0]
849 self.curframe_locals = self.curframe.f_locals
850 self.print_stack_entry(self.stack[self.curindex])
851 self.lineno = None
852
Tim Peters2344fae2001-01-15 00:50:52 +0000853 def do_up(self, arg):
854 if self.curindex == 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000855 print('*** Oldest frame', file=self.stdout)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000856 return
857 try:
858 count = int(arg or 1)
859 except ValueError:
860 print('*** Invalid frame count (%s)' % arg, file=self.stdout)
861 return
862 if count < 0:
863 newframe = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000864 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000865 newframe = max(0, self.curindex - count)
866 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000867 do_u = do_up
868
869 def do_down(self, arg):
870 if self.curindex + 1 == len(self.stack):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000871 print('*** Newest frame', file=self.stdout)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000872 return
873 try:
874 count = int(arg or 1)
875 except ValueError:
876 print('*** Invalid frame count (%s)' % arg, file=self.stdout)
877 return
878 if count < 0:
879 newframe = len(self.stack) - 1
Tim Peters2344fae2001-01-15 00:50:52 +0000880 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000881 newframe = min(len(self.stack) - 1, self.curindex + count)
882 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000883 do_d = do_down
884
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000885 def do_until(self, arg):
886 self.set_until(self.curframe)
887 return 1
888 do_unt = do_until
889
Tim Peters2344fae2001-01-15 00:50:52 +0000890 def do_step(self, arg):
891 self.set_step()
892 return 1
893 do_s = do_step
894
895 def do_next(self, arg):
896 self.set_next(self.curframe)
897 return 1
898 do_n = do_next
899
Guido van Rossumd8faa362007-04-27 19:54:29 +0000900 def do_run(self, arg):
Georg Brandl3078df02009-05-05 09:11:31 +0000901 """Restart program by raising an exception to be caught in the main
902 debugger loop. If arguments were given, set them in sys.argv."""
Guido van Rossumd8faa362007-04-27 19:54:29 +0000903 if arg:
904 import shlex
905 argv0 = sys.argv[0:1]
906 sys.argv = shlex.split(arg)
907 sys.argv[:0] = argv0
908 raise Restart
909
910 do_restart = do_run
911
Tim Peters2344fae2001-01-15 00:50:52 +0000912 def do_return(self, arg):
913 self.set_return(self.curframe)
914 return 1
915 do_r = do_return
916
917 def do_continue(self, arg):
918 self.set_continue()
919 return 1
920 do_c = do_cont = do_continue
921
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000922 def do_jump(self, arg):
923 if self.curindex + 1 != len(self.stack):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000924 print("*** You can only jump within the bottom frame", file=self.stdout)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000925 return
926 try:
927 arg = int(arg)
928 except ValueError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000929 print("*** The 'jump' command requires a line number.", file=self.stdout)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000930 else:
931 try:
932 # Do the jump, fix up our copy of the stack, and display the
933 # new position
934 self.curframe.f_lineno = arg
935 self.stack[self.curindex] = self.stack[self.curindex][0], arg
936 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumb940e112007-01-10 16:19:56 +0000937 except ValueError as e:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000938 print('*** Jump failed:', e, file=self.stdout)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000939 do_j = do_jump
940
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000941 def do_debug(self, arg):
942 sys.settrace(None)
943 globals = self.curframe.f_globals
Benjamin Petersond23f8222009-04-05 19:13:16 +0000944 locals = self.curframe_locals
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000945 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +0000946 p.prompt = "(%s) " % self.prompt.strip()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000947 print("ENTERING RECURSIVE DEBUGGER", file=self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +0000948 sys.call_tracing(p.run, (arg, globals, locals))
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000949 print("LEAVING RECURSIVE DEBUGGER", file=self.stdout)
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000950 sys.settrace(self.trace_dispatch)
951 self.lastcmd = p.lastcmd
952
Tim Peters2344fae2001-01-15 00:50:52 +0000953 def do_quit(self, arg):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000954 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000955 self.set_quit()
956 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000957
Tim Peters2344fae2001-01-15 00:50:52 +0000958 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000959 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000960
Guido van Rossumeef26072003-01-13 21:13:55 +0000961 def do_EOF(self, arg):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000962 print(file=self.stdout)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000963 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000964 self.set_quit()
965 return 1
966
Tim Peters2344fae2001-01-15 00:50:52 +0000967 def do_args(self, arg):
Benjamin Petersond23f8222009-04-05 19:13:16 +0000968 co = self.curframe.f_code
969 dict = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000970 n = co.co_argcount
971 if co.co_flags & 4: n = n+1
972 if co.co_flags & 8: n = n+1
973 for i in range(n):
974 name = co.co_varnames[i]
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000975 print(name, '=', end=' ', file=self.stdout)
976 if name in dict: print(dict[name], file=self.stdout)
977 else: print("*** undefined ***", file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000978 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000979
Tim Peters2344fae2001-01-15 00:50:52 +0000980 def do_retval(self, arg):
Benjamin Petersond23f8222009-04-05 19:13:16 +0000981 if '__return__' in self.curframe_locals:
982 print(self.curframe_locals['__return__'], file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000983 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000984 print('*** Not yet returned!', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000985 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000986
Barry Warsaw210bd202002-11-05 22:40:20 +0000987 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000988 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +0000989 return eval(arg, self.curframe.f_globals, self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000990 except:
991 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000992 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000993 exc_type_name = t
994 else: exc_type_name = t.__name__
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000995 print('***', exc_type_name + ':', repr(v), file=self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +0000996 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000997
Barry Warsaw210bd202002-11-05 22:40:20 +0000998 def do_p(self, arg):
999 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001000 print(repr(self._getval(arg)), file=self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +00001001 except:
1002 pass
Georg Brandlc9879242007-09-04 07:07:56 +00001003 # make "print" an alias of "p" since print isn't a Python statement anymore
1004 do_print = do_p
Barry Warsaw210bd202002-11-05 22:40:20 +00001005
1006 def do_pp(self, arg):
1007 try:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001008 pprint.pprint(self._getval(arg), self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +00001009 except:
1010 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001011
Tim Peters2344fae2001-01-15 00:50:52 +00001012 def do_list(self, arg):
1013 self.lastcmd = 'list'
1014 last = None
Georg Brandla91a94b2010-07-30 07:14:01 +00001015 if arg and arg != '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001016 try:
1017 x = eval(arg, {}, {})
1018 if type(x) == type(()):
1019 first, last = x
1020 first = int(first)
1021 last = int(last)
1022 if last < first:
1023 # Assume it's a count
1024 last = first + last
1025 else:
1026 first = max(1, int(x) - 5)
1027 except:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001028 print('*** Error in argument:', repr(arg), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001029 return
Georg Brandla91a94b2010-07-30 07:14:01 +00001030 elif self.lineno is None or arg == '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001031 first = max(1, self.curframe.f_lineno - 5)
1032 else:
1033 first = self.lineno + 1
1034 if last is None:
1035 last = first + 10
1036 filename = self.curframe.f_code.co_filename
1037 breaklist = self.get_file_breaks(filename)
1038 try:
1039 for lineno in range(first, last+1):
Georg Brandl3078df02009-05-05 09:11:31 +00001040 line = linecache.getline(filename, lineno,
1041 self.curframe.f_globals)
Tim Peters2344fae2001-01-15 00:50:52 +00001042 if not line:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001043 print('[EOF]', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001044 break
1045 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001046 s = repr(lineno).rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +00001047 if len(s) < 4: s = s + ' '
1048 if lineno in breaklist: s = s + 'B'
1049 else: s = s + ' '
1050 if lineno == self.curframe.f_lineno:
1051 s = s + '->'
Guido van Rossumceae3752007-02-09 22:16:54 +00001052 print(s + '\t' + line, end='', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001053 self.lineno = lineno
1054 except KeyboardInterrupt:
1055 pass
1056 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +00001057
Tim Peters2344fae2001-01-15 00:50:52 +00001058 def do_whatis(self, arg):
1059 try:
1060 value = eval(arg, self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +00001061 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +00001062 except:
1063 t, v = sys.exc_info()[:2]
1064 if type(t) == type(''):
1065 exc_type_name = t
1066 else: exc_type_name = t.__name__
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001067 print('***', exc_type_name + ':', repr(v), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001068 return
1069 code = None
1070 # Is it a function?
Neal Norwitz221085d2007-02-25 20:55:47 +00001071 try: code = value.__code__
Tim Peters2344fae2001-01-15 00:50:52 +00001072 except: pass
1073 if code:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001074 print('Function', code.co_name, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001075 return
1076 # Is it an instance method?
Christian Heimesff737952007-11-27 10:40:20 +00001077 try: code = value.__func__.__code__
Tim Peters2344fae2001-01-15 00:50:52 +00001078 except: pass
1079 if code:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001080 print('Method', code.co_name, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001081 return
1082 # None of the above...
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001083 print(type(value), file=self.stdout)
Guido van Rossum8e2ec561993-07-29 09:37:38 +00001084
Tim Peters2344fae2001-01-15 00:50:52 +00001085 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001086 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001087 if len(args) == 0:
Benjamin Petersonbe74a372009-09-11 21:17:13 +00001088 keys = sorted(self.aliases.keys())
Tim Peters2344fae2001-01-15 00:50:52 +00001089 for alias in keys:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001090 print("%s = %s" % (alias, self.aliases[alias]), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001091 return
Guido van Rossum08454592002-07-12 13:10:53 +00001092 if args[0] in self.aliases and len(args) == 1:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001093 print("%s = %s" % (args[0], self.aliases[args[0]]), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001094 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001095 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +00001096
Tim Peters2344fae2001-01-15 00:50:52 +00001097 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001098 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001099 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +00001100 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +00001101 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +00001102
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001103 #list of all the commands making the program resume execution.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001104 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
1105 'do_quit', 'do_jump']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001106
Tim Peters2344fae2001-01-15 00:50:52 +00001107 # Print a traceback starting at the top stack frame.
1108 # The most recently entered frame is printed last;
1109 # this is different from dbx and gdb, but consistent with
1110 # the Python interpreter's stack trace.
1111 # It is also consistent with the up/down commands (which are
1112 # compatible with dbx and gdb: up moves towards 'main()'
1113 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +00001114
Tim Peters2344fae2001-01-15 00:50:52 +00001115 def print_stack_trace(self):
1116 try:
1117 for frame_lineno in self.stack:
1118 self.print_stack_entry(frame_lineno)
1119 except KeyboardInterrupt:
1120 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001121
Tim Peters2344fae2001-01-15 00:50:52 +00001122 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
1123 frame, lineno = frame_lineno
1124 if frame is self.curframe:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001125 print('>', end=' ', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001126 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001127 print(' ', end=' ', file=self.stdout)
1128 print(self.format_stack_entry(frame_lineno,
1129 prompt_prefix), file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001130
Guido van Rossum921c8241992-01-10 14:54:42 +00001131
Georg Brandl02053ee2010-07-18 10:11:03 +00001132 # Help methods (derived from docstring)
Guido van Rossum921c8241992-01-10 14:54:42 +00001133
Tim Peters2344fae2001-01-15 00:50:52 +00001134 def help_help(self):
1135 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001136
Tim Peters2344fae2001-01-15 00:50:52 +00001137 def help_h(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001138 print("""h(elp)
Tim Peters2344fae2001-01-15 00:50:52 +00001139Without argument, print the list of available commands.
1140With a command name as argument, print help about that command
Georg Brandl55353ca2010-07-19 08:02:46 +00001141"help pdb" shows the full pdb documentation
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001142"help exec" gives help on the ! command""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001143
Tim Peters2344fae2001-01-15 00:50:52 +00001144 def help_where(self):
1145 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001146
Tim Peters2344fae2001-01-15 00:50:52 +00001147 def help_w(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001148 print("""w(here)
Tim Peters2344fae2001-01-15 00:50:52 +00001149Print a stack trace, with the most recent frame at the bottom.
1150An arrow indicates the "current frame", which determines the
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001151context of most commands. 'bt' is an alias for this command.""", file=self.stdout)
Guido van Rossum6bd68352001-01-20 17:57:37 +00001152
1153 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +00001154
Tim Peters2344fae2001-01-15 00:50:52 +00001155 def help_down(self):
1156 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001157
Tim Peters2344fae2001-01-15 00:50:52 +00001158 def help_d(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001159 print("""d(own)
Tim Peters2344fae2001-01-15 00:50:52 +00001160Move the current frame one level down in the stack trace
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001161(to a newer frame).""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001162
Tim Peters2344fae2001-01-15 00:50:52 +00001163 def help_up(self):
1164 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001165
Tim Peters2344fae2001-01-15 00:50:52 +00001166 def help_u(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001167 print("""u(p)
Tim Peters2344fae2001-01-15 00:50:52 +00001168Move the current frame one level up in the stack trace
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001169(to an older frame).""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001170
Tim Peters2344fae2001-01-15 00:50:52 +00001171 def help_break(self):
1172 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001173
Tim Peters2344fae2001-01-15 00:50:52 +00001174 def help_b(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001175 print("""b(reak) ([file:]lineno | function) [, condition]
Tim Peters2344fae2001-01-15 00:50:52 +00001176With a line number argument, set a break there in the current
1177file. With a function name, set a break at first executable line
1178of that function. Without argument, list all breaks. If a second
1179argument is present, it is a string specifying an expression
1180which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +00001181
Tim Peters2344fae2001-01-15 00:50:52 +00001182The line number may be prefixed with a filename and a colon,
1183to specify a breakpoint in another file (probably one that
1184hasn't been loaded yet). The file is searched for on sys.path;
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001185the .py suffix may be omitted.""", file=self.stdout)
Guido van Rossumb5699c71998-07-20 23:13:54 +00001186
Tim Peters2344fae2001-01-15 00:50:52 +00001187 def help_clear(self):
1188 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001189
Tim Peters2344fae2001-01-15 00:50:52 +00001190 def help_cl(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001191 print("cl(ear) filename:lineno", file=self.stdout)
1192 print("""cl(ear) [bpnumber [bpnumber...]]
Tim Peters2344fae2001-01-15 00:50:52 +00001193With a space separated list of breakpoint numbers, clear
1194those breakpoints. Without argument, clear all breaks (but
1195first ask confirmation). With a filename:lineno argument,
Georg Brandld348b252008-01-05 20:00:55 +00001196clear all breaks at that line in that file.""", file=self.stdout)
Guido van Rossumb5699c71998-07-20 23:13:54 +00001197
Tim Peters2344fae2001-01-15 00:50:52 +00001198 def help_tbreak(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001199 print("""tbreak same arguments as break, but breakpoint is
1200removed when first hit.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001201
Tim Peters2344fae2001-01-15 00:50:52 +00001202 def help_enable(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001203 print("""enable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +00001204Enables the breakpoints given as a space separated list of
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001205bp numbers.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001206
Tim Peters2344fae2001-01-15 00:50:52 +00001207 def help_disable(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001208 print("""disable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +00001209Disables the breakpoints given as a space separated list of
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001210bp numbers.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001211
Tim Peters2344fae2001-01-15 00:50:52 +00001212 def help_ignore(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001213 print("""ignore bpnumber count
Tim Peters2344fae2001-01-15 00:50:52 +00001214Sets the ignore count for the given breakpoint number. A breakpoint
1215becomes active when the ignore count is zero. When non-zero, the
1216count is decremented each time the breakpoint is reached and the
1217breakpoint is not disabled and any associated condition evaluates
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001218to true.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001219
Tim Peters2344fae2001-01-15 00:50:52 +00001220 def help_condition(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001221 print("""condition bpnumber str_condition
Tim Peters2344fae2001-01-15 00:50:52 +00001222str_condition is a string specifying an expression which
1223must evaluate to true before the breakpoint is honored.
1224If str_condition is absent, any existing condition is removed;
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001225i.e., the breakpoint is made unconditional.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001226
Tim Peters2344fae2001-01-15 00:50:52 +00001227 def help_step(self):
1228 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001229
Tim Peters2344fae2001-01-15 00:50:52 +00001230 def help_s(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001231 print("""s(tep)
Tim Peters2344fae2001-01-15 00:50:52 +00001232Execute the current line, stop at the first possible occasion
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001233(either in a function that is called or in the current function).""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001234
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001235 def help_until(self):
1236 self.help_unt()
1237
1238 def help_unt(self):
1239 print("""unt(il)
1240Continue execution until the line with a number greater than the current
1241one is reached or until the current frame returns""")
1242
Tim Peters2344fae2001-01-15 00:50:52 +00001243 def help_next(self):
1244 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001245
Tim Peters2344fae2001-01-15 00:50:52 +00001246 def help_n(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001247 print("""n(ext)
Tim Peters2344fae2001-01-15 00:50:52 +00001248Continue execution until the next line in the current function
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001249is reached or it returns.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001250
Tim Peters2344fae2001-01-15 00:50:52 +00001251 def help_return(self):
1252 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001253
Tim Peters2344fae2001-01-15 00:50:52 +00001254 def help_r(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001255 print("""r(eturn)
1256Continue execution until the current function returns.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001257
Tim Peters2344fae2001-01-15 00:50:52 +00001258 def help_continue(self):
1259 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001260
Tim Peters2344fae2001-01-15 00:50:52 +00001261 def help_cont(self):
1262 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001263
Tim Peters2344fae2001-01-15 00:50:52 +00001264 def help_c(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001265 print("""c(ont(inue))
1266Continue execution, only stop when a breakpoint is encountered.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001267
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001268 def help_jump(self):
1269 self.help_j()
1270
1271 def help_j(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001272 print("""j(ump) lineno
1273Set the next line that will be executed.""", file=self.stdout)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001274
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001275 def help_debug(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001276 print("""debug code
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001277Enter a recursive debugger that steps through the code argument
1278(which is an arbitrary expression or statement to be executed
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001279in the current environment).""", file=self.stdout)
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001280
Tim Peters2344fae2001-01-15 00:50:52 +00001281 def help_list(self):
1282 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001283
Tim Peters2344fae2001-01-15 00:50:52 +00001284 def help_l(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001285 print("""l(ist) [first [,last]]
Tim Peters2344fae2001-01-15 00:50:52 +00001286List source code for the current file.
1287Without arguments, list 11 lines around the current line
1288or continue the previous listing.
1289With one argument, list 11 lines starting at that line.
1290With two arguments, list the given range;
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001291if the second argument is less than the first, it is a count.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001292
Tim Peters2344fae2001-01-15 00:50:52 +00001293 def help_args(self):
1294 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001295
Tim Peters2344fae2001-01-15 00:50:52 +00001296 def help_a(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001297 print("""a(rgs)
1298Print the arguments of the current function.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001299
Tim Peters2344fae2001-01-15 00:50:52 +00001300 def help_p(self):
Georg Brandlc9879242007-09-04 07:07:56 +00001301 print("""p(rint) expression
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001302Print the value of the expression.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001303
Barry Warsaw210bd202002-11-05 22:40:20 +00001304 def help_pp(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001305 print("""pp expression
1306Pretty-print the value of the expression.""", file=self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +00001307
Tim Peters2344fae2001-01-15 00:50:52 +00001308 def help_exec(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001309 print("""(!) statement
Tim Peters2344fae2001-01-15 00:50:52 +00001310Execute the (one-line) statement in the context of
1311the current stack frame.
1312The exclamation point can be omitted unless the first word
1313of the statement resembles a debugger command.
1314To assign to a global variable you must always prefix the
1315command with a 'global' command, e.g.:
1316(Pdb) global list_options; list_options = ['-l']
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001317(Pdb)""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001318
Guido van Rossumd8faa362007-04-27 19:54:29 +00001319 def help_run(self):
1320 print("""run [args...]
1321Restart the debugged python program. If a string is supplied, it is
1322splitted with "shlex" and the result is used as the new sys.argv.
1323History, breakpoints, actions and debugger options are preserved.
1324"restart" is an alias for "run".""")
1325
1326 help_restart = help_run
1327
Tim Peters2344fae2001-01-15 00:50:52 +00001328 def help_quit(self):
1329 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001330
Tim Peters2344fae2001-01-15 00:50:52 +00001331 def help_q(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001332 print("""q(uit) or exit - Quit from the debugger.
1333The program being executed is aborted.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001334
Guido van Rossumd1c08f32002-04-15 00:48:24 +00001335 help_exit = help_q
1336
Tim Peters2344fae2001-01-15 00:50:52 +00001337 def help_whatis(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001338 print("""whatis arg
1339Prints the type of the argument.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001340
Tim Peters2344fae2001-01-15 00:50:52 +00001341 def help_EOF(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001342 print("""EOF
1343Handles the receipt of EOF as a command.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001344
Tim Peters2344fae2001-01-15 00:50:52 +00001345 def help_alias(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001346 print("""alias [name [command [parameter parameter ...] ]]
Tim Peters2344fae2001-01-15 00:50:52 +00001347Creates an alias called 'name' the executes 'command'. The command
1348must *not* be enclosed in quotes. Replaceable parameters are
1349indicated by %1, %2, and so on, while %* is replaced by all the
1350parameters. If no command is given, the current alias for name
1351is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +00001352
Tim Peters2344fae2001-01-15 00:50:52 +00001353Aliases may be nested and can contain anything that can be
1354legally typed at the pdb prompt. Note! You *can* override
1355internal pdb commands with aliases! Those internal commands
1356are then hidden until the alias is removed. Aliasing is recursively
1357applied to the first word of the command line; all other words
1358in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +00001359
Tim Peters2344fae2001-01-15 00:50:52 +00001360Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +00001361
Tim Peters2344fae2001-01-15 00:50:52 +00001362#Print instance variables (usage "pi classInst")
1363alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +00001364
Tim Peters2344fae2001-01-15 00:50:52 +00001365#Print instance variables in self
1366alias ps pi self
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001367""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001368
Tim Peters2344fae2001-01-15 00:50:52 +00001369 def help_unalias(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001370 print("""unalias name
1371Deletes the specified alias.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001372
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001373 def help_commands(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001374 print("""commands [bpnumber]
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001375(com) ...
1376(com) end
1377(Pdb)
1378
1379Specify a list of commands for breakpoint number bpnumber. The
1380commands themselves appear on the following lines. Type a line
1381containing just 'end' to terminate the commands.
1382
1383To remove all commands from a breakpoint, type commands and
1384follow it immediately with end; that is, give no commands.
1385
1386With no bpnumber argument, commands refers to the last
1387breakpoint set.
1388
1389You can use breakpoint commands to start your program up again.
1390Simply use the continue command, or step, or any other
1391command that resumes execution.
1392
1393Specifying any command resuming execution (currently continue,
1394step, next, return, jump, quit and their abbreviations) terminates
1395the command list (as if that command was immediately followed by end).
1396This is because any time you resume execution
1397(even with a simple next or step), you may encounter
1398another breakpoint--which could have its own command list, leading to
1399ambiguities about which list to execute.
1400
1401 If you use the 'silent' command in the command list, the
1402usual message about stopping at a breakpoint is not printed. This may
1403be desirable for breakpoints that are to print a specific message and
1404then continue. If none of the other commands print anything, you
1405see no sign that the breakpoint was reached.
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001406""", file=self.stdout)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001407
Tim Peters2344fae2001-01-15 00:50:52 +00001408 def help_pdb(self):
1409 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001410
Tim Peters2344fae2001-01-15 00:50:52 +00001411 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001412 """Helper function for break/clear parsing -- may be overridden.
1413
1414 lookupmodule() translates (possibly incomplete) file or module name
1415 into an absolute file name.
1416 """
1417 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001418 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001419 f = os.path.join(sys.path[0], filename)
1420 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1421 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001422 root, ext = os.path.splitext(filename)
1423 if ext == '':
1424 filename = filename + '.py'
1425 if os.path.isabs(filename):
1426 return filename
1427 for dirname in sys.path:
1428 while os.path.islink(dirname):
1429 dirname = os.readlink(dirname)
1430 fullname = os.path.join(dirname, filename)
1431 if os.path.exists(fullname):
1432 return fullname
1433 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001434
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001435 def _runscript(self, filename):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001436 # The script has to run in __main__ namespace (or imports from
1437 # __main__ will break).
1438 #
1439 # So we clear up the __main__ and set several special variables
1440 # (this gets rid of pdb's globals and cleans old variables on restarts).
1441 import __main__
1442 __main__.__dict__.clear()
1443 __main__.__dict__.update({"__name__" : "__main__",
1444 "__file__" : filename,
1445 "__builtins__": __builtins__,
1446 })
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001447
1448 # When bdb sets tracing, a number of call and line events happens
1449 # BEFORE debugger even reaches user's code (and the exact sequence of
1450 # events depends on python version). So we take special measures to
1451 # avoid stopping before we reach the main script (see user_line and
1452 # user_call for details).
1453 self._wait_for_mainpyfile = 1
1454 self.mainpyfile = self.canonic(filename)
1455 self._user_requested_quit = 0
Georg Brandld07ac642009-08-13 07:50:57 +00001456 with open(filename, "rb") as fp:
1457 statement = "exec(compile(%r, %r, 'exec'))" % \
1458 (fp.read(), self.mainpyfile)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001459 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001460
Guido van Rossum35771131992-09-08 11:59:04 +00001461# Simplified interface
1462
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001463def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001464 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001465
1466def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001467 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001468
1469def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001470 # B/W compatibility
1471 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001472
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001473def runcall(*args, **kwds):
1474 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001475
Guido van Rossumb6775db1994-08-01 11:34:53 +00001476def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001477 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001478
1479# Post-Mortem interface
1480
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001481def post_mortem(t=None):
1482 # handling the default
1483 if t is None:
1484 # sys.exc_info() returns (type, value, traceback) if an exception is
1485 # being handled, otherwise it returns None
1486 t = sys.exc_info()[2]
1487 if t is None:
1488 raise ValueError("A valid traceback must be passed if no "
1489 "exception is being handled")
1490
Tim Peters2344fae2001-01-15 00:50:52 +00001491 p = Pdb()
1492 p.reset()
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001493 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001494
1495def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001496 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001497
1498
1499# Main program for testing
1500
Guido van Rossum23efba41992-01-27 16:58:47 +00001501TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001502
Guido van Rossum921c8241992-01-10 14:54:42 +00001503def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001504 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001505
1506# print help
1507def help():
Georg Brandl02053ee2010-07-18 10:11:03 +00001508 import pydoc
1509 pydoc.pager(__doc__)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001510
Georg Brandle0230912010-07-30 08:29:39 +00001511_usage = """\
1512usage: pdb.py [-c command] ... pyfile [arg] ...
1513
1514Debug the Python program given by pyfile.
1515
1516Initial commands are read from .pdbrc files in your home directory
1517and in the current directory, if they exist. Commands supplied with
1518-c are executed after commands from .pdbrc files.
1519
1520To let the script run until an exception occurs, use "-c continue".
1521To let the script run until a given line X in the debugged file, use
1522"-c 'break X' -c continue"."""
1523
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001524def main():
Georg Brandle0230912010-07-30 08:29:39 +00001525 import getopt
1526
1527 opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['--help', '--command='])
1528
1529 if not args:
1530 print(_usage)
Tim Peters2344fae2001-01-15 00:50:52 +00001531 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001532
Georg Brandle0230912010-07-30 08:29:39 +00001533 commands = []
1534 for opt, optarg in opts:
1535 if opt in ['-h', '--help']:
1536 print(_usage)
1537 sys.exit()
1538 elif opt in ['-c', '--command']:
1539 commands.append(optarg)
1540
1541 mainpyfile = args[0] # Get script filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001542 if not os.path.exists(mainpyfile):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001543 print('Error:', mainpyfile, 'does not exist')
Tim Peters2344fae2001-01-15 00:50:52 +00001544 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001545
Georg Brandle0230912010-07-30 08:29:39 +00001546 sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001547
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001548 # Replace pdb's dir with script's dir in front of module search path.
1549 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001550
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001551 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1552 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl3078df02009-05-05 09:11:31 +00001553 # changed by the user from the command line. There is a "restart" command
1554 # which allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001555 pdb = Pdb()
Georg Brandle0230912010-07-30 08:29:39 +00001556 pdb.rcLines.extend(commands)
Georg Brandl1e30bd32010-07-30 07:21:26 +00001557 while True:
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001558 try:
1559 pdb._runscript(mainpyfile)
1560 if pdb._user_requested_quit:
1561 break
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001562 print("The program finished and will be restarted")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001563 except Restart:
1564 print("Restarting", mainpyfile, "with arguments:")
Georg Brandle0230912010-07-30 08:29:39 +00001565 print("\t" + " ".join(args))
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001566 except SystemExit:
1567 # In most cases SystemExit does not warrant a post-mortem session.
Georg Brandle0230912010-07-30 08:29:39 +00001568 print("The program exited via sys.exit(). Exit status:", end=' ')
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001569 print(sys.exc_info()[1])
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001570 except:
1571 traceback.print_exc()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001572 print("Uncaught exception. Entering post mortem debugging")
1573 print("Running 'cont' or 'step' will restart the program")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001574 t = sys.exc_info()[2]
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001575 pdb.interaction(None, t)
Georg Brandl3078df02009-05-05 09:11:31 +00001576 print("Post mortem debugger finished. The " + mainpyfile +
1577 " will be restarted")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001578
1579
1580# When invoked as main program, invoke the debugger on a script
Guido van Rossumd8faa362007-04-27 19:54:29 +00001581if __name__ == '__main__':
1582 import pdb
1583 pdb.main()