blob: d80a29b689e8a3765cf3b171ac6b1d07c446141b [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
Georg Brandl2dfec552010-07-30 08:43:32 +000074d(own) [count]
Georg Brandl02053ee2010-07-18 10:11:03 +000075 Move the current frame count (default one) levels down in the
76 stack trace (to a newer frame).
77
Georg Brandl2dfec552010-07-30 08:43:32 +000078u(p) [count]
Georg Brandl02053ee2010-07-18 10:11:03 +000079 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
Georg Brandl2dfec552010-07-30 08:43:32 +0000143unt(il) [lineno]
144 Without argument, continue execution until the line with a
145 number greater than the current one is reached. With a line
146 number, continue execution until a line with a number greater
147 or equal to that is reached. In both cases, also stop when
148 the current frame returns.
Georg Brandl02053ee2010-07-18 10:11:03 +0000149
Georg Brandl26a0f872010-07-30 08:45:26 +0000150j(ump) lineno
151 Set the next line that will be executed. Only available in
152 the bottom-most frame. This lets you jump back and execute
153 code again, or jump forward to skip code that you don't want
154 to run.
155
156 It should be noted that not all jumps are allowed -- for
157 instance it is not possible to jump into the middle of a
158 for loop or out of a finally clause.
159
Georg Brandl02053ee2010-07-18 10:11:03 +0000160r(eturn)
161 Continue execution until the current function returns.
162
163run [args...]
164 Restart the debugged python program. If a string is supplied
165 it is splitted with "shlex", and the result is used as the new
166 sys.argv. History, breakpoints, actions and debugger options
167 are preserved. "restart" is an alias for "run".
168
169c(ont(inue))
170 Continue execution, only stop when a breakpoint is encountered.
171
172l(ist) [first [,last]]
173 List source code for the current file.
174 Without arguments, list 11 lines around the current line
175 or continue the previous listing.
Georg Brandla91a94b2010-07-30 07:14:01 +0000176 With . as argument, list 11 lines around the current line.
Georg Brandl02053ee2010-07-18 10:11:03 +0000177 With one argument, list 11 lines starting at that line.
178 With two arguments, list the given range;
179 if the second argument is less than the first, it is a count.
180
181a(rgs)
182 Print the argument list of the current function.
183
184p expression
185 Print the value of the expression.
186
187(!) statement
188 Execute the (one-line) statement in the context of the current
189 stack frame. The exclamation point can be omitted unless the
190 first word of the statement resembles a debugger command. To
191 assign to a global variable you must always prefix the command
192 with a 'global' command, e.g.:
193 (Pdb) global list_options; list_options = ['-l']
194 (Pdb)
195
196
197whatis arg
198 Print the type of the argument.
199
200alias [name [command]]
201 Creates an alias called 'name' that executes 'command'. The
202 command must *not* be enclosed in quotes. Replaceable
203 parameters can be indicated by %1, %2, and so on, while %* is
204 replaced by all the parameters. If no command is given, the
205 current alias for name is shown. If no name is given, all
206 aliases are listed.
207
208 Aliases may be nested and can contain anything that can be
209 legally typed at the pdb prompt. Note! You *can* override
210 internal pdb commands with aliases! Those internal commands
211 are then hidden until the alias is removed. Aliasing is
212 recursively applied to the first word of the command line; all
213 other words in the line are left alone.
214
215 As an example, here are two useful aliases (especially when
216 placed in the .pdbrc file):
217
218 # Print instance variables (usage "pi classInst")
219 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
220 # Print instance variables in self
221 alias ps pi self
222
223unalias name
224 Delete the specified alias.
225
226q(uit)
227 Quit from the debugger. The program being executed is aborted.
228"""
Guido van Rossum921c8241992-01-10 14:54:42 +0000229
Guido van Rossum921c8241992-01-10 14:54:42 +0000230import sys
231import linecache
Guido van Rossum23efba41992-01-27 16:58:47 +0000232import cmd
233import bdb
Alexandre Vassalotti1f2ba4b2008-05-16 07:12:44 +0000234from reprlib import Repr
Guido van Rossumb5699c71998-07-20 23:13:54 +0000235import os
Barry Warsaw2bee8fe1999-09-09 16:32:41 +0000236import re
Barry Warsaw210bd202002-11-05 22:40:20 +0000237import pprint
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000238import traceback
Guido van Rossumd8faa362007-04-27 19:54:29 +0000239
240
241class Restart(Exception):
242 """Causes a debugger to be restarted for the debugged python program."""
243 pass
244
Guido van Rossumef1b41b2002-09-10 21:57:14 +0000245# Create a custom safe Repr instance and increase its maxstring.
246# The default of 30 truncates error messages too easily.
247_repr = Repr()
248_repr.maxstring = 200
249_saferepr = _repr.repr
250
Skip Montanaro352674d2001-02-07 23:14:30 +0000251__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
252 "post_mortem", "help"]
253
Barry Warsaw2bee8fe1999-09-09 16:32:41 +0000254def find_function(funcname, filename):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000255 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
Tim Peters2344fae2001-01-15 00:50:52 +0000256 try:
257 fp = open(filename)
258 except IOError:
259 return None
260 # consumer of this info expects the first line to be 1
261 lineno = 1
262 answer = None
263 while 1:
264 line = fp.readline()
265 if line == '':
266 break
267 if cre.match(line):
268 answer = funcname, filename, lineno
269 break
270 lineno = lineno + 1
271 fp.close()
272 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +0000273
274
Guido van Rossuma558e371994-11-10 22:27:35 +0000275# Interaction prompt line will separate file and call info from code
276# text using value of line_prefix string. A newline and arrow may
277# be to your liking. You can set it once pdb is imported using the
278# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +0000279# line_prefix = ': ' # Use this to get the old situation back
280line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +0000281
Guido van Rossum23efba41992-01-27 16:58:47 +0000282class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +0000283
Georg Brandl243ad662009-05-05 09:00:19 +0000284 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None):
285 bdb.Bdb.__init__(self, skip=skip)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000286 cmd.Cmd.__init__(self, completekey, stdin, stdout)
287 if stdout:
288 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000289 self.prompt = '(Pdb) '
290 self.aliases = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000291 self.mainpyfile = ''
292 self._wait_for_mainpyfile = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000293 # Try to load readline if it exists
294 try:
295 import readline
296 except ImportError:
297 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000298
Tim Peters2344fae2001-01-15 00:50:52 +0000299 # Read $HOME/.pdbrc and ./.pdbrc
300 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +0000301 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +0000302 envHome = os.environ['HOME']
303 try:
304 rcFile = open(os.path.join(envHome, ".pdbrc"))
305 except IOError:
306 pass
307 else:
308 for line in rcFile.readlines():
309 self.rcLines.append(line)
310 rcFile.close()
311 try:
312 rcFile = open(".pdbrc")
313 except IOError:
314 pass
315 else:
316 for line in rcFile.readlines():
317 self.rcLines.append(line)
318 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +0000319
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000320 self.commands = {} # associates a command list to breakpoint numbers
Benjamin Petersond23f8222009-04-05 19:13:16 +0000321 self.commands_doprompt = {} # for each bp num, tells if the prompt
322 # must be disp. after execing the cmd list
323 self.commands_silent = {} # for each bp num, tells if the stack trace
324 # must be disp. after execing the cmd list
325 self.commands_defining = False # True while in the process of defining
326 # a command list
327 self.commands_bnum = None # The breakpoint number for which we are
328 # defining a list
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000329
Tim Peters2344fae2001-01-15 00:50:52 +0000330 def reset(self):
331 bdb.Bdb.reset(self)
332 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000333
Tim Peters2344fae2001-01-15 00:50:52 +0000334 def forget(self):
335 self.lineno = None
336 self.stack = []
337 self.curindex = 0
338 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +0000339
Tim Peters2344fae2001-01-15 00:50:52 +0000340 def setup(self, f, t):
341 self.forget()
342 self.stack, self.curindex = self.get_stack(f, t)
343 self.curframe = self.stack[self.curindex][0]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000344 # The f_locals dictionary is updated from the actual frame
345 # locals whenever the .f_locals accessor is called, so we
346 # cache it here to ensure that modifications are not overwritten.
347 self.curframe_locals = self.curframe.f_locals
Georg Brandle0230912010-07-30 08:29:39 +0000348 return self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000349
Tim Peters2344fae2001-01-15 00:50:52 +0000350 # Can be executed earlier than 'setup' if desired
351 def execRcLines(self):
Georg Brandle0230912010-07-30 08:29:39 +0000352 if not self.rcLines:
353 return
354 # local copy because of recursion
355 rcLines = self.rcLines
356 rcLines.reverse()
357 # execute every line only once
358 self.rcLines = []
359 while rcLines:
360 line = rcLines.pop().strip()
361 if line and line[0] != '#':
362 if self.onecmd(line):
363 # if onecmd returns True, the command wants to exit
364 # from the interaction, save leftover rc lines
365 # to execute before next interaction
366 self.rcLines += reversed(rcLines)
367 return True
Guido van Rossum2424f851998-09-11 22:50:09 +0000368
Tim Peters280488b2002-08-23 18:19:30 +0000369 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000370
371 def user_call(self, frame, argument_list):
372 """This method is called when there is the remote possibility
373 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000374 if self._wait_for_mainpyfile:
375 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000376 if self.stop_here(frame):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000377 print('--Call--', file=self.stdout)
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000378 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000379
Tim Peters2344fae2001-01-15 00:50:52 +0000380 def user_line(self, frame):
381 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000382 if self._wait_for_mainpyfile:
383 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
384 or frame.f_lineno<= 0):
385 return
386 self._wait_for_mainpyfile = 0
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000387 if self.bp_commands(frame):
388 self.interaction(frame, None)
389
Georg Brandle0230912010-07-30 08:29:39 +0000390 def bp_commands(self, frame):
Georg Brandl3078df02009-05-05 09:11:31 +0000391 """Call every command that was set for the current active breakpoint
392 (if there is one).
393
394 Returns True if the normal interaction function must be called,
395 False otherwise."""
396 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
397 if getattr(self, "currentbp", False) and \
398 self.currentbp in self.commands:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000399 currentbp = self.currentbp
400 self.currentbp = 0
401 lastcmd_back = self.lastcmd
402 self.setup(frame, None)
403 for line in self.commands[currentbp]:
404 self.onecmd(line)
405 self.lastcmd = lastcmd_back
406 if not self.commands_silent[currentbp]:
407 self.print_stack_entry(self.stack[self.curindex])
408 if self.commands_doprompt[currentbp]:
409 self.cmdloop()
410 self.forget()
411 return
412 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000413
Tim Peters2344fae2001-01-15 00:50:52 +0000414 def user_return(self, frame, return_value):
415 """This function is called when a return trap is set here."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000416 if self._wait_for_mainpyfile:
417 return
Tim Peters2344fae2001-01-15 00:50:52 +0000418 frame.f_locals['__return__'] = return_value
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000419 print('--Return--', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000420 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000421
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000422 def user_exception(self, frame, exc_info):
Tim Peters2344fae2001-01-15 00:50:52 +0000423 """This function is called if an exception occurs,
424 but only if we are to stop at or just below this level."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000425 if self._wait_for_mainpyfile:
426 return
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000427 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000428 frame.f_locals['__exception__'] = exc_type, exc_value
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000429 exc_type_name = exc_type.__name__
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000430 print(exc_type_name + ':', _saferepr(exc_value), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000431 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000432
Tim Peters2344fae2001-01-15 00:50:52 +0000433 # General interaction function
434
435 def interaction(self, frame, traceback):
Georg Brandle0230912010-07-30 08:29:39 +0000436 if self.setup(frame, traceback):
437 # no interaction desired at this time (happens if .pdbrc contains
438 # a command like "continue")
439 self.forget()
440 return
Tim Peters2344fae2001-01-15 00:50:52 +0000441 self.print_stack_entry(self.stack[self.curindex])
442 self.cmdloop()
443 self.forget()
444
Benjamin Petersond23f8222009-04-05 19:13:16 +0000445 def displayhook(self, obj):
446 """Custom displayhook for the exec in default(), which prevents
447 assignment of the _ variable in the builtins.
448 """
Georg Brandl9fa2e022009-09-16 16:40:45 +0000449 # reproduce the behavior of the standard displayhook, not printing None
450 if obj is not None:
451 print(repr(obj))
Benjamin Petersond23f8222009-04-05 19:13:16 +0000452
Tim Peters2344fae2001-01-15 00:50:52 +0000453 def default(self, line):
454 if line[:1] == '!': line = line[1:]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000455 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000456 globals = self.curframe.f_globals
457 try:
458 code = compile(line + '\n', '<stdin>', 'single')
Christian Heimes679db4a2008-01-18 09:56:22 +0000459 save_stdout = sys.stdout
460 save_stdin = sys.stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000461 save_displayhook = sys.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000462 try:
463 sys.stdin = self.stdin
464 sys.stdout = self.stdout
Benjamin Petersond23f8222009-04-05 19:13:16 +0000465 sys.displayhook = self.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000466 exec(code, globals, locals)
467 finally:
468 sys.stdout = save_stdout
469 sys.stdin = save_stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000470 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000471 except:
472 t, v = sys.exc_info()[:2]
473 if type(t) == type(''):
474 exc_type_name = t
475 else: exc_type_name = t.__name__
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000476 print('***', exc_type_name + ':', v, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000477
478 def precmd(self, line):
479 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000480 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000481 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000482 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000483 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000484 line = self.aliases[args[0]]
485 ii = 1
486 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000487 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000488 tmpArg)
489 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000490 line = line.replace("%*", ' '.join(args[1:]))
491 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000492 # split into ';;' separated commands
493 # unless it's an alias command
494 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000495 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000496 if marker >= 0:
497 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000498 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000499 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000500 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000501 return line
502
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000503 def onecmd(self, line):
504 """Interpret the argument as though it had been typed in response
505 to the prompt.
506
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000507 Checks whether this line is typed at the normal prompt or in
508 a breakpoint command list definition.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000509 """
510 if not self.commands_defining:
511 return cmd.Cmd.onecmd(self, line)
512 else:
513 return self.handle_command_def(line)
514
515 def handle_command_def(self,line):
Georg Brandl44f8bf92010-07-30 08:54:49 +0000516 """Handles one command line during command list definition."""
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000517 cmd, arg, line = self.parseline(line)
Georg Brandl44f8bf92010-07-30 08:54:49 +0000518 if not cmd:
519 return
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000520 if cmd == 'silent':
521 self.commands_silent[self.commands_bnum] = True
522 return # continue to handle other cmd def in the cmd list
523 elif cmd == 'end':
524 self.cmdqueue = []
525 return 1 # end of cmd list
526 cmdlist = self.commands[self.commands_bnum]
Georg Brandl44f8bf92010-07-30 08:54:49 +0000527 if arg:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000528 cmdlist.append(cmd+' '+arg)
529 else:
530 cmdlist.append(cmd)
531 # Determine if we must stop
532 try:
533 func = getattr(self, 'do_' + cmd)
534 except AttributeError:
535 func = self.default
Georg Brandl3078df02009-05-05 09:11:31 +0000536 # one of the resuming commands
537 if func.__name__ in self.commands_resuming:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000538 self.commands_doprompt[self.commands_bnum] = False
539 self.cmdqueue = []
540 return 1
541 return
542
Tim Peters2344fae2001-01-15 00:50:52 +0000543 # Command definitions, called by cmdloop()
544 # The argument is the remaining string on the command line
545 # Return true to exit from the command loop
546
547 do_h = cmd.Cmd.do_help
548
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000549 def do_commands(self, arg):
Georg Brandl3078df02009-05-05 09:11:31 +0000550 """Defines a list of commands associated to a breakpoint.
551
552 Those commands will be executed whenever the breakpoint causes
553 the program to stop execution."""
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000554 if not arg:
555 bnum = len(bdb.Breakpoint.bpbynumber)-1
556 else:
557 try:
558 bnum = int(arg)
559 except:
Georg Brandl3078df02009-05-05 09:11:31 +0000560 print("Usage : commands [bnum]\n ...\n end",
561 file=self.stdout)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000562 return
563 self.commands_bnum = bnum
564 self.commands[bnum] = []
565 self.commands_doprompt[bnum] = True
566 self.commands_silent[bnum] = False
567 prompt_back = self.prompt
568 self.prompt = '(com) '
569 self.commands_defining = True
Georg Brandl44f8bf92010-07-30 08:54:49 +0000570 try:
571 self.cmdloop()
572 finally:
573 self.commands_defining = False
574 self.prompt = prompt_back
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000575
Tim Peters2344fae2001-01-15 00:50:52 +0000576 def do_break(self, arg, temporary = 0):
577 # break [ ([filename:]lineno | function) [, "condition"] ]
578 if not arg:
579 if self.breaks: # There's at least one
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000580 print("Num Type Disp Enb Where", file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000581 for bp in bdb.Breakpoint.bpbynumber:
582 if bp:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000583 bp.bpprint(self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000584 return
585 # parse arguments; comma has lowest precedence
586 # and cannot occur in filename
587 filename = None
588 lineno = None
589 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000590 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000591 if comma > 0:
592 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000593 cond = arg[comma+1:].lstrip()
594 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000595 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000596 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000597 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000598 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000599 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000600 f = self.lookupmodule(filename)
601 if not f:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000602 print('*** ', repr(filename), end=' ', file=self.stdout)
603 print('not found from sys.path', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000604 return
605 else:
606 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000607 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000608 try:
609 lineno = int(arg)
Guido van Rossumb940e112007-01-10 16:19:56 +0000610 except ValueError as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000611 print('*** Bad lineno:', arg, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000612 return
613 else:
614 # no colon; can be lineno or function
615 try:
616 lineno = int(arg)
617 except ValueError:
618 try:
619 func = eval(arg,
620 self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +0000621 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000622 except:
623 func = arg
624 try:
Christian Heimesff737952007-11-27 10:40:20 +0000625 if hasattr(func, '__func__'):
626 func = func.__func__
Neal Norwitz221085d2007-02-25 20:55:47 +0000627 code = func.__code__
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000628 #use co_name to identify the bkpt (function names
629 #could be aliased, but co_name is invariant)
630 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000631 lineno = code.co_firstlineno
632 filename = code.co_filename
633 except:
634 # last thing to try
635 (ok, filename, ln) = self.lineinfo(arg)
636 if not ok:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000637 print('*** The specified object', end=' ', file=self.stdout)
638 print(repr(arg), end=' ', file=self.stdout)
639 print('is not a function', file=self.stdout)
640 print('or was not found along sys.path.', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000641 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000642 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000643 lineno = int(ln)
644 if not filename:
645 filename = self.defaultFile()
646 # Check for reasonable breakpoint
647 line = self.checkline(filename, lineno)
648 if line:
649 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000650 err = self.set_break(filename, line, temporary, cond, funcname)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000651 if err: print('***', err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000652 else:
653 bp = self.get_breaks(filename, line)[-1]
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000654 print("Breakpoint %d at %s:%d" % (bp.number,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000655 bp.file,
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000656 bp.line), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000657
658 # To be overridden in derived debuggers
659 def defaultFile(self):
660 """Produce a reasonable default."""
661 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000662 if filename == '<string>' and self.mainpyfile:
663 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000664 return filename
665
666 do_b = do_break
667
668 def do_tbreak(self, arg):
669 self.do_break(arg, 1)
670
671 def lineinfo(self, identifier):
672 failed = (None, None, None)
673 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000674 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000675 if len(idstring) == 1:
676 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000677 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000678 elif len(idstring) == 3:
679 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000680 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000681 else:
682 return failed
683 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000684 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000685 # Protection for derived debuggers
686 if parts[0] == 'self':
687 del parts[0]
688 if len(parts) == 0:
689 return failed
690 # Best first guess at file to look at
691 fname = self.defaultFile()
692 if len(parts) == 1:
693 item = parts[0]
694 else:
695 # More than one part.
696 # First is module, second is method/class
697 f = self.lookupmodule(parts[0])
698 if f:
699 fname = f
700 item = parts[1]
701 answer = find_function(item, fname)
702 return answer or failed
703
704 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000705 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000706
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000707 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
708 line or EOF). Warning: testing is not comprehensive.
709 """
Georg Brandl1e30bd32010-07-30 07:21:26 +0000710 # this method should be callable before starting debugging, so default
711 # to "no globals" if there is no current frame
712 globs = self.curframe.f_globals if hasattr(self, 'curframe') else None
713 line = linecache.getline(filename, lineno, globs)
Tim Peters2344fae2001-01-15 00:50:52 +0000714 if not line:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000715 print('End of file', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000716 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000717 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000718 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000719 if (not line or (line[0] == '#') or
720 (line[:3] == '"""') or line[:3] == "'''"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000721 print('*** Blank or comment', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000722 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000723 return lineno
724
725 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000726 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000727 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000728 try:
729 i = int(i)
730 except ValueError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000731 print('Breakpoint index %r is not a number' % i, file=self.stdout)
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000732 continue
733
734 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000735 print('No breakpoint numbered', i, file=self.stdout)
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000736 continue
737
738 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000739 if bp:
740 bp.enable()
741
742 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000743 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000744 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000745 try:
746 i = int(i)
747 except ValueError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000748 print('Breakpoint index %r is not a number' % i, file=self.stdout)
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000749 continue
Tim Petersf545baa2003-06-15 23:26:30 +0000750
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000751 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000752 print('No breakpoint numbered', i, file=self.stdout)
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000753 continue
754
755 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000756 if bp:
757 bp.disable()
758
759 def do_condition(self, arg):
760 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000761 args = arg.split(' ', 1)
Thomas Woutersb2137042007-02-01 18:02:27 +0000762 try:
763 bpnum = int(args[0].strip())
764 except ValueError:
765 # something went wrong
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000766 print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000767 return
Tim Peters2344fae2001-01-15 00:50:52 +0000768 try:
769 cond = args[1]
770 except:
771 cond = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000772 try:
773 bp = bdb.Breakpoint.bpbynumber[bpnum]
774 except IndexError:
Neal Norwitz752abd02008-05-13 04:55:24 +0000775 print('Breakpoint index %r is not valid' % args[0],
776 file=self.stdout)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000777 return
Tim Peters2344fae2001-01-15 00:50:52 +0000778 if bp:
779 bp.cond = cond
780 if not cond:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000781 print('Breakpoint', bpnum, end=' ', file=self.stdout)
782 print('is now unconditional.', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000783
784 def do_ignore(self,arg):
785 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000786 args = arg.split()
Thomas Woutersb2137042007-02-01 18:02:27 +0000787 try:
788 bpnum = int(args[0].strip())
789 except ValueError:
790 # something went wrong
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000791 print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000792 return
Tim Peters2344fae2001-01-15 00:50:52 +0000793 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000794 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000795 except:
796 count = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +0000797 try:
798 bp = bdb.Breakpoint.bpbynumber[bpnum]
799 except IndexError:
Neal Norwitz752abd02008-05-13 04:55:24 +0000800 print('Breakpoint index %r is not valid' % args[0],
801 file=self.stdout)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000802 return
Tim Peters2344fae2001-01-15 00:50:52 +0000803 if bp:
804 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000805 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000806 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000807 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000808 reply = reply + '%d crossings' % count
809 else:
810 reply = reply + '1 crossing'
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000811 print(reply + ' of breakpoint %d.' % bpnum, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000812 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000813 print('Will stop next time breakpoint', end=' ', file=self.stdout)
814 print(bpnum, 'is reached.', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000815
816 def do_clear(self, arg):
817 """Three possibilities, tried in this order:
818 clear -> clear all breaks, ask for confirmation
819 clear file:lineno -> clear all breaks at file:lineno
820 clear bpno bpno ... -> clear breakpoints by number"""
821 if not arg:
822 try:
Guido van Rossumc5b6ab02007-05-27 09:19:52 +0000823 reply = input('Clear all breaks? ')
Tim Peters2344fae2001-01-15 00:50:52 +0000824 except EOFError:
825 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000826 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000827 if reply in ('y', 'yes'):
828 self.clear_all_breaks()
829 return
830 if ':' in arg:
831 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000832 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000833 filename = arg[:i]
834 arg = arg[i+1:]
835 try:
836 lineno = int(arg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000837 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000838 err = "Invalid line number (%s)" % arg
839 else:
840 err = self.clear_break(filename, lineno)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000841 if err: print('***', err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000842 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000843 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000844 for i in numberlist:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000845 try:
846 i = int(i)
847 except ValueError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000848 print('Breakpoint index %r is not a number' % i, file=self.stdout)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000849 continue
850
Georg Brandl6d2b3462005-08-24 07:36:17 +0000851 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000852 print('No breakpoint numbered', i, file=self.stdout)
Georg Brandl6d2b3462005-08-24 07:36:17 +0000853 continue
Tim Peters2344fae2001-01-15 00:50:52 +0000854 err = self.clear_bpbynumber(i)
855 if err:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000856 print('***', err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000857 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000858 print('Deleted breakpoint', i, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000859 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
860
861 def do_where(self, arg):
862 self.print_stack_trace()
863 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000864 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000865
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000866 def _select_frame(self, number):
867 assert 0 <= number < len(self.stack)
868 self.curindex = number
869 self.curframe = self.stack[self.curindex][0]
870 self.curframe_locals = self.curframe.f_locals
871 self.print_stack_entry(self.stack[self.curindex])
872 self.lineno = None
873
Tim Peters2344fae2001-01-15 00:50:52 +0000874 def do_up(self, arg):
875 if self.curindex == 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000876 print('*** Oldest frame', file=self.stdout)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000877 return
878 try:
879 count = int(arg or 1)
880 except ValueError:
881 print('*** Invalid frame count (%s)' % arg, file=self.stdout)
882 return
883 if count < 0:
884 newframe = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000885 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000886 newframe = max(0, self.curindex - count)
887 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000888 do_u = do_up
889
890 def do_down(self, arg):
891 if self.curindex + 1 == len(self.stack):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000892 print('*** Newest frame', file=self.stdout)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000893 return
894 try:
895 count = int(arg or 1)
896 except ValueError:
897 print('*** Invalid frame count (%s)' % arg, file=self.stdout)
898 return
899 if count < 0:
900 newframe = len(self.stack) - 1
Tim Peters2344fae2001-01-15 00:50:52 +0000901 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000902 newframe = min(len(self.stack) - 1, self.curindex + count)
903 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000904 do_d = do_down
905
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000906 def do_until(self, arg):
Georg Brandl2dfec552010-07-30 08:43:32 +0000907 if arg:
908 try:
909 lineno = int(arg)
910 except ValueError:
911 print('*** Error in argument:', repr(arg), file=self.stdout)
912 return
913 if lineno <= self.curframe.f_lineno:
914 print('*** "until" line number is smaller than current '
915 'line number', file=self.stdout)
916 return
917 else:
918 lineno = None
919 self.set_until(self.curframe, lineno)
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000920 return 1
921 do_unt = do_until
922
Tim Peters2344fae2001-01-15 00:50:52 +0000923 def do_step(self, arg):
924 self.set_step()
925 return 1
926 do_s = do_step
927
928 def do_next(self, arg):
929 self.set_next(self.curframe)
930 return 1
931 do_n = do_next
932
Guido van Rossumd8faa362007-04-27 19:54:29 +0000933 def do_run(self, arg):
Georg Brandl3078df02009-05-05 09:11:31 +0000934 """Restart program by raising an exception to be caught in the main
935 debugger loop. If arguments were given, set them in sys.argv."""
Guido van Rossumd8faa362007-04-27 19:54:29 +0000936 if arg:
937 import shlex
938 argv0 = sys.argv[0:1]
939 sys.argv = shlex.split(arg)
940 sys.argv[:0] = argv0
941 raise Restart
942
943 do_restart = do_run
944
Tim Peters2344fae2001-01-15 00:50:52 +0000945 def do_return(self, arg):
946 self.set_return(self.curframe)
947 return 1
948 do_r = do_return
949
950 def do_continue(self, arg):
951 self.set_continue()
952 return 1
953 do_c = do_cont = do_continue
954
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000955 def do_jump(self, arg):
956 if self.curindex + 1 != len(self.stack):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000957 print("*** You can only jump within the bottom frame", file=self.stdout)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000958 return
959 try:
960 arg = int(arg)
961 except ValueError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000962 print("*** The 'jump' command requires a line number.", file=self.stdout)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000963 else:
964 try:
965 # Do the jump, fix up our copy of the stack, and display the
966 # new position
967 self.curframe.f_lineno = arg
968 self.stack[self.curindex] = self.stack[self.curindex][0], arg
969 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumb940e112007-01-10 16:19:56 +0000970 except ValueError as e:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000971 print('*** Jump failed:', e, file=self.stdout)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000972 do_j = do_jump
973
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000974 def do_debug(self, arg):
975 sys.settrace(None)
976 globals = self.curframe.f_globals
Benjamin Petersond23f8222009-04-05 19:13:16 +0000977 locals = self.curframe_locals
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000978 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +0000979 p.prompt = "(%s) " % self.prompt.strip()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000980 print("ENTERING RECURSIVE DEBUGGER", file=self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +0000981 sys.call_tracing(p.run, (arg, globals, locals))
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000982 print("LEAVING RECURSIVE DEBUGGER", file=self.stdout)
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000983 sys.settrace(self.trace_dispatch)
984 self.lastcmd = p.lastcmd
985
Tim Peters2344fae2001-01-15 00:50:52 +0000986 def do_quit(self, arg):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000987 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000988 self.set_quit()
989 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000990
Tim Peters2344fae2001-01-15 00:50:52 +0000991 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000992 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000993
Guido van Rossumeef26072003-01-13 21:13:55 +0000994 def do_EOF(self, arg):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000995 print(file=self.stdout)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000996 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000997 self.set_quit()
998 return 1
999
Tim Peters2344fae2001-01-15 00:50:52 +00001000 def do_args(self, arg):
Benjamin Petersond23f8222009-04-05 19:13:16 +00001001 co = self.curframe.f_code
1002 dict = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +00001003 n = co.co_argcount
1004 if co.co_flags & 4: n = n+1
1005 if co.co_flags & 8: n = n+1
1006 for i in range(n):
1007 name = co.co_varnames[i]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001008 print(name, '=', end=' ', file=self.stdout)
1009 if name in dict: print(dict[name], file=self.stdout)
1010 else: print("*** undefined ***", file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001011 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +00001012
Tim Peters2344fae2001-01-15 00:50:52 +00001013 def do_retval(self, arg):
Benjamin Petersond23f8222009-04-05 19:13:16 +00001014 if '__return__' in self.curframe_locals:
1015 print(self.curframe_locals['__return__'], file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001016 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001017 print('*** Not yet returned!', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001018 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +00001019
Barry Warsaw210bd202002-11-05 22:40:20 +00001020 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +00001021 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +00001022 return eval(arg, self.curframe.f_globals, self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +00001023 except:
1024 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +00001025 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +00001026 exc_type_name = t
1027 else: exc_type_name = t.__name__
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001028 print('***', exc_type_name + ':', repr(v), file=self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +00001029 raise
Guido van Rossum2424f851998-09-11 22:50:09 +00001030
Barry Warsaw210bd202002-11-05 22:40:20 +00001031 def do_p(self, arg):
1032 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001033 print(repr(self._getval(arg)), file=self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +00001034 except:
1035 pass
Georg Brandlc9879242007-09-04 07:07:56 +00001036 # make "print" an alias of "p" since print isn't a Python statement anymore
1037 do_print = do_p
Barry Warsaw210bd202002-11-05 22:40:20 +00001038
1039 def do_pp(self, arg):
1040 try:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001041 pprint.pprint(self._getval(arg), self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +00001042 except:
1043 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001044
Tim Peters2344fae2001-01-15 00:50:52 +00001045 def do_list(self, arg):
1046 self.lastcmd = 'list'
1047 last = None
Georg Brandla91a94b2010-07-30 07:14:01 +00001048 if arg and arg != '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001049 try:
1050 x = eval(arg, {}, {})
1051 if type(x) == type(()):
1052 first, last = x
1053 first = int(first)
1054 last = int(last)
1055 if last < first:
1056 # Assume it's a count
1057 last = first + last
1058 else:
1059 first = max(1, int(x) - 5)
1060 except:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001061 print('*** Error in argument:', repr(arg), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001062 return
Georg Brandla91a94b2010-07-30 07:14:01 +00001063 elif self.lineno is None or arg == '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001064 first = max(1, self.curframe.f_lineno - 5)
1065 else:
1066 first = self.lineno + 1
1067 if last is None:
1068 last = first + 10
1069 filename = self.curframe.f_code.co_filename
1070 breaklist = self.get_file_breaks(filename)
1071 try:
1072 for lineno in range(first, last+1):
Georg Brandl3078df02009-05-05 09:11:31 +00001073 line = linecache.getline(filename, lineno,
1074 self.curframe.f_globals)
Tim Peters2344fae2001-01-15 00:50:52 +00001075 if not line:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001076 print('[EOF]', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001077 break
1078 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001079 s = repr(lineno).rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +00001080 if len(s) < 4: s = s + ' '
1081 if lineno in breaklist: s = s + 'B'
1082 else: s = s + ' '
1083 if lineno == self.curframe.f_lineno:
1084 s = s + '->'
Guido van Rossumceae3752007-02-09 22:16:54 +00001085 print(s + '\t' + line, end='', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001086 self.lineno = lineno
1087 except KeyboardInterrupt:
1088 pass
1089 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +00001090
Tim Peters2344fae2001-01-15 00:50:52 +00001091 def do_whatis(self, arg):
1092 try:
1093 value = eval(arg, self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +00001094 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +00001095 except:
1096 t, v = sys.exc_info()[:2]
1097 if type(t) == type(''):
1098 exc_type_name = t
1099 else: exc_type_name = t.__name__
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001100 print('***', exc_type_name + ':', repr(v), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001101 return
1102 code = None
1103 # Is it a function?
Neal Norwitz221085d2007-02-25 20:55:47 +00001104 try: code = value.__code__
Tim Peters2344fae2001-01-15 00:50:52 +00001105 except: pass
1106 if code:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001107 print('Function', code.co_name, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001108 return
1109 # Is it an instance method?
Christian Heimesff737952007-11-27 10:40:20 +00001110 try: code = value.__func__.__code__
Tim Peters2344fae2001-01-15 00:50:52 +00001111 except: pass
1112 if code:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001113 print('Method', code.co_name, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001114 return
1115 # None of the above...
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001116 print(type(value), file=self.stdout)
Guido van Rossum8e2ec561993-07-29 09:37:38 +00001117
Tim Peters2344fae2001-01-15 00:50:52 +00001118 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001119 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001120 if len(args) == 0:
Benjamin Petersonbe74a372009-09-11 21:17:13 +00001121 keys = sorted(self.aliases.keys())
Tim Peters2344fae2001-01-15 00:50:52 +00001122 for alias in keys:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001123 print("%s = %s" % (alias, self.aliases[alias]), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001124 return
Guido van Rossum08454592002-07-12 13:10:53 +00001125 if args[0] in self.aliases and len(args) == 1:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001126 print("%s = %s" % (args[0], self.aliases[args[0]]), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001127 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001128 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +00001129
Tim Peters2344fae2001-01-15 00:50:52 +00001130 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001131 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001132 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +00001133 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +00001134 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +00001135
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001136 #list of all the commands making the program resume execution.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001137 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
1138 'do_quit', 'do_jump']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001139
Tim Peters2344fae2001-01-15 00:50:52 +00001140 # Print a traceback starting at the top stack frame.
1141 # The most recently entered frame is printed last;
1142 # this is different from dbx and gdb, but consistent with
1143 # the Python interpreter's stack trace.
1144 # It is also consistent with the up/down commands (which are
1145 # compatible with dbx and gdb: up moves towards 'main()'
1146 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +00001147
Tim Peters2344fae2001-01-15 00:50:52 +00001148 def print_stack_trace(self):
1149 try:
1150 for frame_lineno in self.stack:
1151 self.print_stack_entry(frame_lineno)
1152 except KeyboardInterrupt:
1153 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001154
Tim Peters2344fae2001-01-15 00:50:52 +00001155 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
1156 frame, lineno = frame_lineno
1157 if frame is self.curframe:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001158 print('>', end=' ', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001159 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001160 print(' ', end=' ', file=self.stdout)
1161 print(self.format_stack_entry(frame_lineno,
1162 prompt_prefix), file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001163
Guido van Rossum921c8241992-01-10 14:54:42 +00001164
Georg Brandl02053ee2010-07-18 10:11:03 +00001165 # Help methods (derived from docstring)
Guido van Rossum921c8241992-01-10 14:54:42 +00001166
Tim Peters2344fae2001-01-15 00:50:52 +00001167 def help_help(self):
1168 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001169
Tim Peters2344fae2001-01-15 00:50:52 +00001170 def help_h(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001171 print("""h(elp)
Tim Peters2344fae2001-01-15 00:50:52 +00001172Without argument, print the list of available commands.
1173With a command name as argument, print help about that command
Georg Brandl55353ca2010-07-19 08:02:46 +00001174"help pdb" shows the full pdb documentation
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001175"help exec" gives help on the ! command""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001176
Tim Peters2344fae2001-01-15 00:50:52 +00001177 def help_where(self):
1178 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001179
Tim Peters2344fae2001-01-15 00:50:52 +00001180 def help_w(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001181 print("""w(here)
Tim Peters2344fae2001-01-15 00:50:52 +00001182Print a stack trace, with the most recent frame at the bottom.
1183An arrow indicates the "current frame", which determines the
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001184context of most commands. 'bt' is an alias for this command.""", file=self.stdout)
Guido van Rossum6bd68352001-01-20 17:57:37 +00001185
1186 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +00001187
Tim Peters2344fae2001-01-15 00:50:52 +00001188 def help_down(self):
1189 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001190
Tim Peters2344fae2001-01-15 00:50:52 +00001191 def help_d(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001192 print("""d(own)
Tim Peters2344fae2001-01-15 00:50:52 +00001193Move the current frame one level down in the stack trace
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001194(to a newer frame).""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001195
Tim Peters2344fae2001-01-15 00:50:52 +00001196 def help_up(self):
1197 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001198
Tim Peters2344fae2001-01-15 00:50:52 +00001199 def help_u(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001200 print("""u(p)
Tim Peters2344fae2001-01-15 00:50:52 +00001201Move the current frame one level up in the stack trace
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001202(to an older frame).""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001203
Tim Peters2344fae2001-01-15 00:50:52 +00001204 def help_break(self):
1205 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001206
Tim Peters2344fae2001-01-15 00:50:52 +00001207 def help_b(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001208 print("""b(reak) ([file:]lineno | function) [, condition]
Tim Peters2344fae2001-01-15 00:50:52 +00001209With a line number argument, set a break there in the current
1210file. With a function name, set a break at first executable line
1211of that function. Without argument, list all breaks. If a second
1212argument is present, it is a string specifying an expression
1213which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +00001214
Tim Peters2344fae2001-01-15 00:50:52 +00001215The line number may be prefixed with a filename and a colon,
1216to specify a breakpoint in another file (probably one that
1217hasn't been loaded yet). The file is searched for on sys.path;
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001218the .py suffix may be omitted.""", file=self.stdout)
Guido van Rossumb5699c71998-07-20 23:13:54 +00001219
Tim Peters2344fae2001-01-15 00:50:52 +00001220 def help_clear(self):
1221 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001222
Tim Peters2344fae2001-01-15 00:50:52 +00001223 def help_cl(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001224 print("cl(ear) filename:lineno", file=self.stdout)
1225 print("""cl(ear) [bpnumber [bpnumber...]]
Tim Peters2344fae2001-01-15 00:50:52 +00001226With a space separated list of breakpoint numbers, clear
1227those breakpoints. Without argument, clear all breaks (but
1228first ask confirmation). With a filename:lineno argument,
Georg Brandld348b252008-01-05 20:00:55 +00001229clear all breaks at that line in that file.""", file=self.stdout)
Guido van Rossumb5699c71998-07-20 23:13:54 +00001230
Tim Peters2344fae2001-01-15 00:50:52 +00001231 def help_tbreak(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001232 print("""tbreak same arguments as break, but breakpoint is
1233removed when first hit.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001234
Tim Peters2344fae2001-01-15 00:50:52 +00001235 def help_enable(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001236 print("""enable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +00001237Enables the breakpoints given as a space separated list of
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001238bp numbers.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001239
Tim Peters2344fae2001-01-15 00:50:52 +00001240 def help_disable(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001241 print("""disable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +00001242Disables the breakpoints given as a space separated list of
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001243bp numbers.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001244
Tim Peters2344fae2001-01-15 00:50:52 +00001245 def help_ignore(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001246 print("""ignore bpnumber count
Tim Peters2344fae2001-01-15 00:50:52 +00001247Sets the ignore count for the given breakpoint number. A breakpoint
1248becomes active when the ignore count is zero. When non-zero, the
1249count is decremented each time the breakpoint is reached and the
1250breakpoint is not disabled and any associated condition evaluates
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001251to true.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001252
Tim Peters2344fae2001-01-15 00:50:52 +00001253 def help_condition(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001254 print("""condition bpnumber str_condition
Tim Peters2344fae2001-01-15 00:50:52 +00001255str_condition is a string specifying an expression which
1256must evaluate to true before the breakpoint is honored.
1257If str_condition is absent, any existing condition is removed;
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001258i.e., the breakpoint is made unconditional.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001259
Tim Peters2344fae2001-01-15 00:50:52 +00001260 def help_step(self):
1261 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001262
Tim Peters2344fae2001-01-15 00:50:52 +00001263 def help_s(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001264 print("""s(tep)
Tim Peters2344fae2001-01-15 00:50:52 +00001265Execute the current line, stop at the first possible occasion
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001266(either in a function that is called or in the current function).""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001267
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001268 def help_until(self):
1269 self.help_unt()
1270
1271 def help_unt(self):
1272 print("""unt(il)
1273Continue execution until the line with a number greater than the current
1274one is reached or until the current frame returns""")
1275
Tim Peters2344fae2001-01-15 00:50:52 +00001276 def help_next(self):
1277 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001278
Tim Peters2344fae2001-01-15 00:50:52 +00001279 def help_n(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001280 print("""n(ext)
Tim Peters2344fae2001-01-15 00:50:52 +00001281Continue execution until the next line in the current function
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001282is reached or it returns.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001283
Tim Peters2344fae2001-01-15 00:50:52 +00001284 def help_return(self):
1285 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001286
Tim Peters2344fae2001-01-15 00:50:52 +00001287 def help_r(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001288 print("""r(eturn)
1289Continue execution until the current function returns.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001290
Tim Peters2344fae2001-01-15 00:50:52 +00001291 def help_continue(self):
1292 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001293
Tim Peters2344fae2001-01-15 00:50:52 +00001294 def help_cont(self):
1295 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001296
Tim Peters2344fae2001-01-15 00:50:52 +00001297 def help_c(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001298 print("""c(ont(inue))
1299Continue execution, only stop when a breakpoint is encountered.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001300
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001301 def help_jump(self):
1302 self.help_j()
1303
1304 def help_j(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001305 print("""j(ump) lineno
1306Set the next line that will be executed.""", file=self.stdout)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001307
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001308 def help_debug(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001309 print("""debug code
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001310Enter a recursive debugger that steps through the code argument
1311(which is an arbitrary expression or statement to be executed
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001312in the current environment).""", file=self.stdout)
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001313
Tim Peters2344fae2001-01-15 00:50:52 +00001314 def help_list(self):
1315 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001316
Tim Peters2344fae2001-01-15 00:50:52 +00001317 def help_l(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001318 print("""l(ist) [first [,last]]
Tim Peters2344fae2001-01-15 00:50:52 +00001319List source code for the current file.
1320Without arguments, list 11 lines around the current line
1321or continue the previous listing.
1322With one argument, list 11 lines starting at that line.
1323With two arguments, list the given range;
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001324if the second argument is less than the first, it is a count.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001325
Tim Peters2344fae2001-01-15 00:50:52 +00001326 def help_args(self):
1327 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001328
Tim Peters2344fae2001-01-15 00:50:52 +00001329 def help_a(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001330 print("""a(rgs)
1331Print the arguments of the current function.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001332
Tim Peters2344fae2001-01-15 00:50:52 +00001333 def help_p(self):
Georg Brandlc9879242007-09-04 07:07:56 +00001334 print("""p(rint) expression
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001335Print the value of the expression.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001336
Barry Warsaw210bd202002-11-05 22:40:20 +00001337 def help_pp(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001338 print("""pp expression
1339Pretty-print the value of the expression.""", file=self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +00001340
Tim Peters2344fae2001-01-15 00:50:52 +00001341 def help_exec(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001342 print("""(!) statement
Tim Peters2344fae2001-01-15 00:50:52 +00001343Execute the (one-line) statement in the context of
1344the current stack frame.
1345The exclamation point can be omitted unless the first word
1346of the statement resembles a debugger command.
1347To assign to a global variable you must always prefix the
1348command with a 'global' command, e.g.:
1349(Pdb) global list_options; list_options = ['-l']
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001350(Pdb)""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001351
Guido van Rossumd8faa362007-04-27 19:54:29 +00001352 def help_run(self):
1353 print("""run [args...]
1354Restart the debugged python program. If a string is supplied, it is
1355splitted with "shlex" and the result is used as the new sys.argv.
1356History, breakpoints, actions and debugger options are preserved.
1357"restart" is an alias for "run".""")
1358
1359 help_restart = help_run
1360
Tim Peters2344fae2001-01-15 00:50:52 +00001361 def help_quit(self):
1362 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001363
Tim Peters2344fae2001-01-15 00:50:52 +00001364 def help_q(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001365 print("""q(uit) or exit - Quit from the debugger.
1366The program being executed is aborted.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001367
Guido van Rossumd1c08f32002-04-15 00:48:24 +00001368 help_exit = help_q
1369
Tim Peters2344fae2001-01-15 00:50:52 +00001370 def help_whatis(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001371 print("""whatis arg
1372Prints the type of the argument.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001373
Tim Peters2344fae2001-01-15 00:50:52 +00001374 def help_EOF(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001375 print("""EOF
1376Handles the receipt of EOF as a command.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001377
Tim Peters2344fae2001-01-15 00:50:52 +00001378 def help_alias(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001379 print("""alias [name [command [parameter parameter ...] ]]
Tim Peters2344fae2001-01-15 00:50:52 +00001380Creates an alias called 'name' the executes 'command'. The command
1381must *not* be enclosed in quotes. Replaceable parameters are
1382indicated by %1, %2, and so on, while %* is replaced by all the
1383parameters. If no command is given, the current alias for name
1384is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +00001385
Tim Peters2344fae2001-01-15 00:50:52 +00001386Aliases may be nested and can contain anything that can be
1387legally typed at the pdb prompt. Note! You *can* override
1388internal pdb commands with aliases! Those internal commands
1389are then hidden until the alias is removed. Aliasing is recursively
1390applied to the first word of the command line; all other words
1391in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +00001392
Tim Peters2344fae2001-01-15 00:50:52 +00001393Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +00001394
Tim Peters2344fae2001-01-15 00:50:52 +00001395#Print instance variables (usage "pi classInst")
1396alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +00001397
Tim Peters2344fae2001-01-15 00:50:52 +00001398#Print instance variables in self
1399alias ps pi self
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001400""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001401
Tim Peters2344fae2001-01-15 00:50:52 +00001402 def help_unalias(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001403 print("""unalias name
1404Deletes the specified alias.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001405
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001406 def help_commands(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001407 print("""commands [bpnumber]
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001408(com) ...
1409(com) end
1410(Pdb)
1411
1412Specify a list of commands for breakpoint number bpnumber. The
1413commands themselves appear on the following lines. Type a line
1414containing just 'end' to terminate the commands.
1415
1416To remove all commands from a breakpoint, type commands and
1417follow it immediately with end; that is, give no commands.
1418
1419With no bpnumber argument, commands refers to the last
1420breakpoint set.
1421
1422You can use breakpoint commands to start your program up again.
1423Simply use the continue command, or step, or any other
1424command that resumes execution.
1425
1426Specifying any command resuming execution (currently continue,
1427step, next, return, jump, quit and their abbreviations) terminates
1428the command list (as if that command was immediately followed by end).
1429This is because any time you resume execution
1430(even with a simple next or step), you may encounter
1431another breakpoint--which could have its own command list, leading to
1432ambiguities about which list to execute.
1433
1434 If you use the 'silent' command in the command list, the
1435usual message about stopping at a breakpoint is not printed. This may
1436be desirable for breakpoints that are to print a specific message and
1437then continue. If none of the other commands print anything, you
1438see no sign that the breakpoint was reached.
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001439""", file=self.stdout)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001440
Tim Peters2344fae2001-01-15 00:50:52 +00001441 def help_pdb(self):
1442 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001443
Tim Peters2344fae2001-01-15 00:50:52 +00001444 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001445 """Helper function for break/clear parsing -- may be overridden.
1446
1447 lookupmodule() translates (possibly incomplete) file or module name
1448 into an absolute file name.
1449 """
1450 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001451 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001452 f = os.path.join(sys.path[0], filename)
1453 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1454 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001455 root, ext = os.path.splitext(filename)
1456 if ext == '':
1457 filename = filename + '.py'
1458 if os.path.isabs(filename):
1459 return filename
1460 for dirname in sys.path:
1461 while os.path.islink(dirname):
1462 dirname = os.readlink(dirname)
1463 fullname = os.path.join(dirname, filename)
1464 if os.path.exists(fullname):
1465 return fullname
1466 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001467
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001468 def _runscript(self, filename):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001469 # The script has to run in __main__ namespace (or imports from
1470 # __main__ will break).
1471 #
1472 # So we clear up the __main__ and set several special variables
1473 # (this gets rid of pdb's globals and cleans old variables on restarts).
1474 import __main__
1475 __main__.__dict__.clear()
1476 __main__.__dict__.update({"__name__" : "__main__",
1477 "__file__" : filename,
1478 "__builtins__": __builtins__,
1479 })
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001480
1481 # When bdb sets tracing, a number of call and line events happens
1482 # BEFORE debugger even reaches user's code (and the exact sequence of
1483 # events depends on python version). So we take special measures to
1484 # avoid stopping before we reach the main script (see user_line and
1485 # user_call for details).
1486 self._wait_for_mainpyfile = 1
1487 self.mainpyfile = self.canonic(filename)
1488 self._user_requested_quit = 0
Georg Brandld07ac642009-08-13 07:50:57 +00001489 with open(filename, "rb") as fp:
1490 statement = "exec(compile(%r, %r, 'exec'))" % \
1491 (fp.read(), self.mainpyfile)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001492 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001493
Guido van Rossum35771131992-09-08 11:59:04 +00001494# Simplified interface
1495
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001496def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001497 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001498
1499def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001500 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001501
1502def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001503 # B/W compatibility
1504 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001505
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001506def runcall(*args, **kwds):
1507 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001508
Guido van Rossumb6775db1994-08-01 11:34:53 +00001509def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001510 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001511
1512# Post-Mortem interface
1513
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001514def post_mortem(t=None):
1515 # handling the default
1516 if t is None:
1517 # sys.exc_info() returns (type, value, traceback) if an exception is
1518 # being handled, otherwise it returns None
1519 t = sys.exc_info()[2]
1520 if t is None:
1521 raise ValueError("A valid traceback must be passed if no "
1522 "exception is being handled")
1523
Tim Peters2344fae2001-01-15 00:50:52 +00001524 p = Pdb()
1525 p.reset()
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001526 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001527
1528def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001529 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001530
1531
1532# Main program for testing
1533
Guido van Rossum23efba41992-01-27 16:58:47 +00001534TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001535
Guido van Rossum921c8241992-01-10 14:54:42 +00001536def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001537 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001538
1539# print help
1540def help():
Georg Brandl02053ee2010-07-18 10:11:03 +00001541 import pydoc
1542 pydoc.pager(__doc__)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001543
Georg Brandle0230912010-07-30 08:29:39 +00001544_usage = """\
1545usage: pdb.py [-c command] ... pyfile [arg] ...
1546
1547Debug the Python program given by pyfile.
1548
1549Initial commands are read from .pdbrc files in your home directory
1550and in the current directory, if they exist. Commands supplied with
1551-c are executed after commands from .pdbrc files.
1552
1553To let the script run until an exception occurs, use "-c continue".
Georg Brandl2dfec552010-07-30 08:43:32 +00001554To let the script run up to a given line X in the debugged file, use
1555"-c 'until X'"."""
Georg Brandle0230912010-07-30 08:29:39 +00001556
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001557def main():
Georg Brandle0230912010-07-30 08:29:39 +00001558 import getopt
1559
1560 opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['--help', '--command='])
1561
1562 if not args:
1563 print(_usage)
Tim Peters2344fae2001-01-15 00:50:52 +00001564 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001565
Georg Brandle0230912010-07-30 08:29:39 +00001566 commands = []
1567 for opt, optarg in opts:
1568 if opt in ['-h', '--help']:
1569 print(_usage)
1570 sys.exit()
1571 elif opt in ['-c', '--command']:
1572 commands.append(optarg)
1573
1574 mainpyfile = args[0] # Get script filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001575 if not os.path.exists(mainpyfile):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001576 print('Error:', mainpyfile, 'does not exist')
Tim Peters2344fae2001-01-15 00:50:52 +00001577 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001578
Georg Brandle0230912010-07-30 08:29:39 +00001579 sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001580
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001581 # Replace pdb's dir with script's dir in front of module search path.
1582 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001583
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001584 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1585 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl3078df02009-05-05 09:11:31 +00001586 # changed by the user from the command line. There is a "restart" command
1587 # which allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001588 pdb = Pdb()
Georg Brandle0230912010-07-30 08:29:39 +00001589 pdb.rcLines.extend(commands)
Georg Brandl1e30bd32010-07-30 07:21:26 +00001590 while True:
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001591 try:
1592 pdb._runscript(mainpyfile)
1593 if pdb._user_requested_quit:
1594 break
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001595 print("The program finished and will be restarted")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001596 except Restart:
1597 print("Restarting", mainpyfile, "with arguments:")
Georg Brandle0230912010-07-30 08:29:39 +00001598 print("\t" + " ".join(args))
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001599 except SystemExit:
1600 # In most cases SystemExit does not warrant a post-mortem session.
Georg Brandle0230912010-07-30 08:29:39 +00001601 print("The program exited via sys.exit(). Exit status:", end=' ')
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001602 print(sys.exc_info()[1])
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001603 except:
1604 traceback.print_exc()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001605 print("Uncaught exception. Entering post mortem debugging")
1606 print("Running 'cont' or 'step' will restart the program")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001607 t = sys.exc_info()[2]
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001608 pdb.interaction(None, t)
Georg Brandl3078df02009-05-05 09:11:31 +00001609 print("Post mortem debugger finished. The " + mainpyfile +
1610 " will be restarted")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001611
1612
1613# When invoked as main program, invoke the debugger on a script
Guido van Rossumd8faa362007-04-27 19:54:29 +00001614if __name__ == '__main__':
1615 import pdb
1616 pdb.main()