blob: 5b12ffa20988173d60bff67a74c4aff86c2ac816 [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.
163 With one argument, list 11 lines starting at that line.
164 With two arguments, list the given range;
165 if the second argument is less than the first, it is a count.
166
167a(rgs)
168 Print the argument list of the current function.
169
170p expression
171 Print the value of the expression.
172
173(!) statement
174 Execute the (one-line) statement in the context of the current
175 stack frame. The exclamation point can be omitted unless the
176 first word of the statement resembles a debugger command. To
177 assign to a global variable you must always prefix the command
178 with a 'global' command, e.g.:
179 (Pdb) global list_options; list_options = ['-l']
180 (Pdb)
181
182
183whatis arg
184 Print the type of the argument.
185
186alias [name [command]]
187 Creates an alias called 'name' that executes 'command'. The
188 command must *not* be enclosed in quotes. Replaceable
189 parameters can be indicated by %1, %2, and so on, while %* is
190 replaced by all the parameters. If no command is given, the
191 current alias for name is shown. If no name is given, all
192 aliases are listed.
193
194 Aliases may be nested and can contain anything that can be
195 legally typed at the pdb prompt. Note! You *can* override
196 internal pdb commands with aliases! Those internal commands
197 are then hidden until the alias is removed. Aliasing is
198 recursively applied to the first word of the command line; all
199 other words in the line are left alone.
200
201 As an example, here are two useful aliases (especially when
202 placed in the .pdbrc file):
203
204 # Print instance variables (usage "pi classInst")
205 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
206 # Print instance variables in self
207 alias ps pi self
208
209unalias name
210 Delete the specified alias.
211
212q(uit)
213 Quit from the debugger. The program being executed is aborted.
214"""
Guido van Rossum921c8241992-01-10 14:54:42 +0000215
Guido van Rossum921c8241992-01-10 14:54:42 +0000216import sys
217import linecache
Guido van Rossum23efba41992-01-27 16:58:47 +0000218import cmd
219import bdb
Alexandre Vassalotti1f2ba4b2008-05-16 07:12:44 +0000220from reprlib import Repr
Guido van Rossumb5699c71998-07-20 23:13:54 +0000221import os
Barry Warsaw2bee8fe1999-09-09 16:32:41 +0000222import re
Barry Warsaw210bd202002-11-05 22:40:20 +0000223import pprint
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000224import traceback
Guido van Rossumd8faa362007-04-27 19:54:29 +0000225
226
227class Restart(Exception):
228 """Causes a debugger to be restarted for the debugged python program."""
229 pass
230
Guido van Rossumef1b41b2002-09-10 21:57:14 +0000231# Create a custom safe Repr instance and increase its maxstring.
232# The default of 30 truncates error messages too easily.
233_repr = Repr()
234_repr.maxstring = 200
235_saferepr = _repr.repr
236
Skip Montanaro352674d2001-02-07 23:14:30 +0000237__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
238 "post_mortem", "help"]
239
Barry Warsaw2bee8fe1999-09-09 16:32:41 +0000240def find_function(funcname, filename):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000241 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
Tim Peters2344fae2001-01-15 00:50:52 +0000242 try:
243 fp = open(filename)
244 except IOError:
245 return None
246 # consumer of this info expects the first line to be 1
247 lineno = 1
248 answer = None
249 while 1:
250 line = fp.readline()
251 if line == '':
252 break
253 if cre.match(line):
254 answer = funcname, filename, lineno
255 break
256 lineno = lineno + 1
257 fp.close()
258 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +0000259
260
Guido van Rossuma558e371994-11-10 22:27:35 +0000261# Interaction prompt line will separate file and call info from code
262# text using value of line_prefix string. A newline and arrow may
263# be to your liking. You can set it once pdb is imported using the
264# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +0000265# line_prefix = ': ' # Use this to get the old situation back
266line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +0000267
Guido van Rossum23efba41992-01-27 16:58:47 +0000268class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +0000269
Georg Brandl243ad662009-05-05 09:00:19 +0000270 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None):
271 bdb.Bdb.__init__(self, skip=skip)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000272 cmd.Cmd.__init__(self, completekey, stdin, stdout)
273 if stdout:
274 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000275 self.prompt = '(Pdb) '
276 self.aliases = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000277 self.mainpyfile = ''
278 self._wait_for_mainpyfile = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000279 # Try to load readline if it exists
280 try:
281 import readline
282 except ImportError:
283 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000284
Tim Peters2344fae2001-01-15 00:50:52 +0000285 # Read $HOME/.pdbrc and ./.pdbrc
286 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +0000287 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +0000288 envHome = os.environ['HOME']
289 try:
290 rcFile = open(os.path.join(envHome, ".pdbrc"))
291 except IOError:
292 pass
293 else:
294 for line in rcFile.readlines():
295 self.rcLines.append(line)
296 rcFile.close()
297 try:
298 rcFile = open(".pdbrc")
299 except IOError:
300 pass
301 else:
302 for line in rcFile.readlines():
303 self.rcLines.append(line)
304 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +0000305
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000306 self.commands = {} # associates a command list to breakpoint numbers
Benjamin Petersond23f8222009-04-05 19:13:16 +0000307 self.commands_doprompt = {} # for each bp num, tells if the prompt
308 # must be disp. after execing the cmd list
309 self.commands_silent = {} # for each bp num, tells if the stack trace
310 # must be disp. after execing the cmd list
311 self.commands_defining = False # True while in the process of defining
312 # a command list
313 self.commands_bnum = None # The breakpoint number for which we are
314 # defining a list
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000315
Tim Peters2344fae2001-01-15 00:50:52 +0000316 def reset(self):
317 bdb.Bdb.reset(self)
318 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000319
Tim Peters2344fae2001-01-15 00:50:52 +0000320 def forget(self):
321 self.lineno = None
322 self.stack = []
323 self.curindex = 0
324 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +0000325
Tim Peters2344fae2001-01-15 00:50:52 +0000326 def setup(self, f, t):
327 self.forget()
328 self.stack, self.curindex = self.get_stack(f, t)
329 self.curframe = self.stack[self.curindex][0]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000330 # The f_locals dictionary is updated from the actual frame
331 # locals whenever the .f_locals accessor is called, so we
332 # cache it here to ensure that modifications are not overwritten.
333 self.curframe_locals = self.curframe.f_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000334 self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000335
Tim Peters2344fae2001-01-15 00:50:52 +0000336 # Can be executed earlier than 'setup' if desired
337 def execRcLines(self):
338 if self.rcLines:
339 # Make local copy because of recursion
340 rcLines = self.rcLines
341 # executed only once
342 self.rcLines = []
343 for line in rcLines:
344 line = line[:-1]
Guido van Rossum08454592002-07-12 13:10:53 +0000345 if len(line) > 0 and line[0] != '#':
346 self.onecmd(line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000347
Tim Peters280488b2002-08-23 18:19:30 +0000348 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000349
350 def user_call(self, frame, argument_list):
351 """This method is called when there is the remote possibility
352 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000353 if self._wait_for_mainpyfile:
354 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000355 if self.stop_here(frame):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000356 print('--Call--', file=self.stdout)
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000357 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000358
Tim Peters2344fae2001-01-15 00:50:52 +0000359 def user_line(self, frame):
360 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000361 if self._wait_for_mainpyfile:
362 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
363 or frame.f_lineno<= 0):
364 return
365 self._wait_for_mainpyfile = 0
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000366 if self.bp_commands(frame):
367 self.interaction(frame, None)
368
369 def bp_commands(self,frame):
Georg Brandl3078df02009-05-05 09:11:31 +0000370 """Call every command that was set for the current active breakpoint
371 (if there is one).
372
373 Returns True if the normal interaction function must be called,
374 False otherwise."""
375 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
376 if getattr(self, "currentbp", False) and \
377 self.currentbp in self.commands:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000378 currentbp = self.currentbp
379 self.currentbp = 0
380 lastcmd_back = self.lastcmd
381 self.setup(frame, None)
382 for line in self.commands[currentbp]:
383 self.onecmd(line)
384 self.lastcmd = lastcmd_back
385 if not self.commands_silent[currentbp]:
386 self.print_stack_entry(self.stack[self.curindex])
387 if self.commands_doprompt[currentbp]:
388 self.cmdloop()
389 self.forget()
390 return
391 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000392
Tim Peters2344fae2001-01-15 00:50:52 +0000393 def user_return(self, frame, return_value):
394 """This function is called when a return trap is set here."""
395 frame.f_locals['__return__'] = return_value
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000396 print('--Return--', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000397 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000398
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000399 def user_exception(self, frame, exc_info):
Tim Peters2344fae2001-01-15 00:50:52 +0000400 """This function is called if an exception occurs,
401 but only if we are to stop at or just below this level."""
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000402 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000403 frame.f_locals['__exception__'] = exc_type, exc_value
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000404 exc_type_name = exc_type.__name__
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000405 print(exc_type_name + ':', _saferepr(exc_value), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000406 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000407
Tim Peters2344fae2001-01-15 00:50:52 +0000408 # General interaction function
409
410 def interaction(self, frame, traceback):
411 self.setup(frame, traceback)
412 self.print_stack_entry(self.stack[self.curindex])
413 self.cmdloop()
414 self.forget()
415
Benjamin Petersond23f8222009-04-05 19:13:16 +0000416 def displayhook(self, obj):
417 """Custom displayhook for the exec in default(), which prevents
418 assignment of the _ variable in the builtins.
419 """
Georg Brandl9fa2e022009-09-16 16:40:45 +0000420 # reproduce the behavior of the standard displayhook, not printing None
421 if obj is not None:
422 print(repr(obj))
Benjamin Petersond23f8222009-04-05 19:13:16 +0000423
Tim Peters2344fae2001-01-15 00:50:52 +0000424 def default(self, line):
425 if line[:1] == '!': line = line[1:]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000426 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000427 globals = self.curframe.f_globals
428 try:
429 code = compile(line + '\n', '<stdin>', 'single')
Christian Heimes679db4a2008-01-18 09:56:22 +0000430 save_stdout = sys.stdout
431 save_stdin = sys.stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000432 save_displayhook = sys.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000433 try:
434 sys.stdin = self.stdin
435 sys.stdout = self.stdout
Benjamin Petersond23f8222009-04-05 19:13:16 +0000436 sys.displayhook = self.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000437 exec(code, globals, locals)
438 finally:
439 sys.stdout = save_stdout
440 sys.stdin = save_stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000441 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000442 except:
443 t, v = sys.exc_info()[:2]
444 if type(t) == type(''):
445 exc_type_name = t
446 else: exc_type_name = t.__name__
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000447 print('***', exc_type_name + ':', v, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000448
449 def precmd(self, line):
450 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000451 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000452 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000453 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000454 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000455 line = self.aliases[args[0]]
456 ii = 1
457 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000458 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000459 tmpArg)
460 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000461 line = line.replace("%*", ' '.join(args[1:]))
462 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000463 # split into ';;' separated commands
464 # unless it's an alias command
465 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000466 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000467 if marker >= 0:
468 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000469 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000470 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000471 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000472 return line
473
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000474 def onecmd(self, line):
475 """Interpret the argument as though it had been typed in response
476 to the prompt.
477
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000478 Checks whether this line is typed at the normal prompt or in
479 a breakpoint command list definition.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000480 """
481 if not self.commands_defining:
482 return cmd.Cmd.onecmd(self, line)
483 else:
484 return self.handle_command_def(line)
485
486 def handle_command_def(self,line):
487 """ Handles one command line during command list definition. """
488 cmd, arg, line = self.parseline(line)
489 if cmd == 'silent':
490 self.commands_silent[self.commands_bnum] = True
491 return # continue to handle other cmd def in the cmd list
492 elif cmd == 'end':
493 self.cmdqueue = []
494 return 1 # end of cmd list
495 cmdlist = self.commands[self.commands_bnum]
496 if (arg):
497 cmdlist.append(cmd+' '+arg)
498 else:
499 cmdlist.append(cmd)
500 # Determine if we must stop
501 try:
502 func = getattr(self, 'do_' + cmd)
503 except AttributeError:
504 func = self.default
Georg Brandl3078df02009-05-05 09:11:31 +0000505 # one of the resuming commands
506 if func.__name__ in self.commands_resuming:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000507 self.commands_doprompt[self.commands_bnum] = False
508 self.cmdqueue = []
509 return 1
510 return
511
Tim Peters2344fae2001-01-15 00:50:52 +0000512 # Command definitions, called by cmdloop()
513 # The argument is the remaining string on the command line
514 # Return true to exit from the command loop
515
516 do_h = cmd.Cmd.do_help
517
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000518 def do_commands(self, arg):
Georg Brandl3078df02009-05-05 09:11:31 +0000519 """Defines a list of commands associated to a breakpoint.
520
521 Those commands will be executed whenever the breakpoint causes
522 the program to stop execution."""
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000523 if not arg:
524 bnum = len(bdb.Breakpoint.bpbynumber)-1
525 else:
526 try:
527 bnum = int(arg)
528 except:
Georg Brandl3078df02009-05-05 09:11:31 +0000529 print("Usage : commands [bnum]\n ...\n end",
530 file=self.stdout)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000531 return
532 self.commands_bnum = bnum
533 self.commands[bnum] = []
534 self.commands_doprompt[bnum] = True
535 self.commands_silent[bnum] = False
536 prompt_back = self.prompt
537 self.prompt = '(com) '
538 self.commands_defining = True
539 self.cmdloop()
540 self.commands_defining = False
541 self.prompt = prompt_back
542
Tim Peters2344fae2001-01-15 00:50:52 +0000543 def do_break(self, arg, temporary = 0):
544 # break [ ([filename:]lineno | function) [, "condition"] ]
545 if not arg:
546 if self.breaks: # There's at least one
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000547 print("Num Type Disp Enb Where", file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000548 for bp in bdb.Breakpoint.bpbynumber:
549 if bp:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000550 bp.bpprint(self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000551 return
552 # parse arguments; comma has lowest precedence
553 # and cannot occur in filename
554 filename = None
555 lineno = None
556 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000557 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000558 if comma > 0:
559 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000560 cond = arg[comma+1:].lstrip()
561 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000562 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000563 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000564 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000565 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000566 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000567 f = self.lookupmodule(filename)
568 if not f:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000569 print('*** ', repr(filename), end=' ', file=self.stdout)
570 print('not found from sys.path', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000571 return
572 else:
573 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000574 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000575 try:
576 lineno = int(arg)
Guido van Rossumb940e112007-01-10 16:19:56 +0000577 except ValueError as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000578 print('*** Bad lineno:', arg, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000579 return
580 else:
581 # no colon; can be lineno or function
582 try:
583 lineno = int(arg)
584 except ValueError:
585 try:
586 func = eval(arg,
587 self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +0000588 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000589 except:
590 func = arg
591 try:
Christian Heimesff737952007-11-27 10:40:20 +0000592 if hasattr(func, '__func__'):
593 func = func.__func__
Neal Norwitz221085d2007-02-25 20:55:47 +0000594 code = func.__code__
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000595 #use co_name to identify the bkpt (function names
596 #could be aliased, but co_name is invariant)
597 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000598 lineno = code.co_firstlineno
599 filename = code.co_filename
600 except:
601 # last thing to try
602 (ok, filename, ln) = self.lineinfo(arg)
603 if not ok:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000604 print('*** The specified object', end=' ', file=self.stdout)
605 print(repr(arg), end=' ', file=self.stdout)
606 print('is not a function', file=self.stdout)
607 print('or was not found along sys.path.', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000608 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000609 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000610 lineno = int(ln)
611 if not filename:
612 filename = self.defaultFile()
613 # Check for reasonable breakpoint
614 line = self.checkline(filename, lineno)
615 if line:
616 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000617 err = self.set_break(filename, line, temporary, cond, funcname)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000618 if err: print('***', err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000619 else:
620 bp = self.get_breaks(filename, line)[-1]
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000621 print("Breakpoint %d at %s:%d" % (bp.number,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000622 bp.file,
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000623 bp.line), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000624
625 # To be overridden in derived debuggers
626 def defaultFile(self):
627 """Produce a reasonable default."""
628 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000629 if filename == '<string>' and self.mainpyfile:
630 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000631 return filename
632
633 do_b = do_break
634
635 def do_tbreak(self, arg):
636 self.do_break(arg, 1)
637
638 def lineinfo(self, identifier):
639 failed = (None, None, None)
640 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000641 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000642 if len(idstring) == 1:
643 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000644 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000645 elif len(idstring) == 3:
646 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000647 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000648 else:
649 return failed
650 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000651 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000652 # Protection for derived debuggers
653 if parts[0] == 'self':
654 del parts[0]
655 if len(parts) == 0:
656 return failed
657 # Best first guess at file to look at
658 fname = self.defaultFile()
659 if len(parts) == 1:
660 item = parts[0]
661 else:
662 # More than one part.
663 # First is module, second is method/class
664 f = self.lookupmodule(parts[0])
665 if f:
666 fname = f
667 item = parts[1]
668 answer = find_function(item, fname)
669 return answer or failed
670
671 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000672 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000673
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000674 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
675 line or EOF). Warning: testing is not comprehensive.
676 """
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000677 line = linecache.getline(filename, lineno, self.curframe.f_globals)
Tim Peters2344fae2001-01-15 00:50:52 +0000678 if not line:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000679 print('End of file', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000680 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000681 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000682 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000683 if (not line or (line[0] == '#') or
684 (line[:3] == '"""') or line[:3] == "'''"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000685 print('*** Blank or comment', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000686 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000687 return lineno
688
689 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000690 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000691 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000692 try:
693 i = int(i)
694 except ValueError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000695 print('Breakpoint index %r is not a number' % i, file=self.stdout)
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000696 continue
697
698 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000699 print('No breakpoint numbered', i, file=self.stdout)
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000700 continue
701
702 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000703 if bp:
704 bp.enable()
705
706 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000707 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000708 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000709 try:
710 i = int(i)
711 except ValueError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000712 print('Breakpoint index %r is not a number' % i, file=self.stdout)
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000713 continue
Tim Petersf545baa2003-06-15 23:26:30 +0000714
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000715 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000716 print('No breakpoint numbered', i, file=self.stdout)
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000717 continue
718
719 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000720 if bp:
721 bp.disable()
722
723 def do_condition(self, arg):
724 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000725 args = arg.split(' ', 1)
Thomas Woutersb2137042007-02-01 18:02:27 +0000726 try:
727 bpnum = int(args[0].strip())
728 except ValueError:
729 # something went wrong
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000730 print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000731 return
Tim Peters2344fae2001-01-15 00:50:52 +0000732 try:
733 cond = args[1]
734 except:
735 cond = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000736 try:
737 bp = bdb.Breakpoint.bpbynumber[bpnum]
738 except IndexError:
Neal Norwitz752abd02008-05-13 04:55:24 +0000739 print('Breakpoint index %r is not valid' % args[0],
740 file=self.stdout)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000741 return
Tim Peters2344fae2001-01-15 00:50:52 +0000742 if bp:
743 bp.cond = cond
744 if not cond:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000745 print('Breakpoint', bpnum, end=' ', file=self.stdout)
746 print('is now unconditional.', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000747
748 def do_ignore(self,arg):
749 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000750 args = arg.split()
Thomas Woutersb2137042007-02-01 18:02:27 +0000751 try:
752 bpnum = int(args[0].strip())
753 except ValueError:
754 # something went wrong
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000755 print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000756 return
Tim Peters2344fae2001-01-15 00:50:52 +0000757 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000758 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000759 except:
760 count = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +0000761 try:
762 bp = bdb.Breakpoint.bpbynumber[bpnum]
763 except IndexError:
Neal Norwitz752abd02008-05-13 04:55:24 +0000764 print('Breakpoint index %r is not valid' % args[0],
765 file=self.stdout)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000766 return
Tim Peters2344fae2001-01-15 00:50:52 +0000767 if bp:
768 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000769 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000770 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000771 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000772 reply = reply + '%d crossings' % count
773 else:
774 reply = reply + '1 crossing'
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000775 print(reply + ' of breakpoint %d.' % bpnum, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000776 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000777 print('Will stop next time breakpoint', end=' ', file=self.stdout)
778 print(bpnum, 'is reached.', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000779
780 def do_clear(self, arg):
781 """Three possibilities, tried in this order:
782 clear -> clear all breaks, ask for confirmation
783 clear file:lineno -> clear all breaks at file:lineno
784 clear bpno bpno ... -> clear breakpoints by number"""
785 if not arg:
786 try:
Guido van Rossumc5b6ab02007-05-27 09:19:52 +0000787 reply = input('Clear all breaks? ')
Tim Peters2344fae2001-01-15 00:50:52 +0000788 except EOFError:
789 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000790 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000791 if reply in ('y', 'yes'):
792 self.clear_all_breaks()
793 return
794 if ':' in arg:
795 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000796 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000797 filename = arg[:i]
798 arg = arg[i+1:]
799 try:
800 lineno = int(arg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000801 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000802 err = "Invalid line number (%s)" % arg
803 else:
804 err = self.clear_break(filename, lineno)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000805 if err: print('***', err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000806 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000807 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000808 for i in numberlist:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000809 try:
810 i = int(i)
811 except ValueError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000812 print('Breakpoint index %r is not a number' % i, file=self.stdout)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000813 continue
814
Georg Brandl6d2b3462005-08-24 07:36:17 +0000815 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000816 print('No breakpoint numbered', i, file=self.stdout)
Georg Brandl6d2b3462005-08-24 07:36:17 +0000817 continue
Tim Peters2344fae2001-01-15 00:50:52 +0000818 err = self.clear_bpbynumber(i)
819 if err:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000820 print('***', err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000821 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000822 print('Deleted breakpoint', i, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000823 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
824
825 def do_where(self, arg):
826 self.print_stack_trace()
827 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000828 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000829
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000830 def _select_frame(self, number):
831 assert 0 <= number < len(self.stack)
832 self.curindex = number
833 self.curframe = self.stack[self.curindex][0]
834 self.curframe_locals = self.curframe.f_locals
835 self.print_stack_entry(self.stack[self.curindex])
836 self.lineno = None
837
Tim Peters2344fae2001-01-15 00:50:52 +0000838 def do_up(self, arg):
839 if self.curindex == 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000840 print('*** Oldest frame', file=self.stdout)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000841 return
842 try:
843 count = int(arg or 1)
844 except ValueError:
845 print('*** Invalid frame count (%s)' % arg, file=self.stdout)
846 return
847 if count < 0:
848 newframe = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000849 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000850 newframe = max(0, self.curindex - count)
851 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000852 do_u = do_up
853
854 def do_down(self, arg):
855 if self.curindex + 1 == len(self.stack):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000856 print('*** Newest frame', file=self.stdout)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000857 return
858 try:
859 count = int(arg or 1)
860 except ValueError:
861 print('*** Invalid frame count (%s)' % arg, file=self.stdout)
862 return
863 if count < 0:
864 newframe = len(self.stack) - 1
Tim Peters2344fae2001-01-15 00:50:52 +0000865 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000866 newframe = min(len(self.stack) - 1, self.curindex + count)
867 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000868 do_d = do_down
869
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000870 def do_until(self, arg):
871 self.set_until(self.curframe)
872 return 1
873 do_unt = do_until
874
Tim Peters2344fae2001-01-15 00:50:52 +0000875 def do_step(self, arg):
876 self.set_step()
877 return 1
878 do_s = do_step
879
880 def do_next(self, arg):
881 self.set_next(self.curframe)
882 return 1
883 do_n = do_next
884
Guido van Rossumd8faa362007-04-27 19:54:29 +0000885 def do_run(self, arg):
Georg Brandl3078df02009-05-05 09:11:31 +0000886 """Restart program by raising an exception to be caught in the main
887 debugger loop. If arguments were given, set them in sys.argv."""
Guido van Rossumd8faa362007-04-27 19:54:29 +0000888 if arg:
889 import shlex
890 argv0 = sys.argv[0:1]
891 sys.argv = shlex.split(arg)
892 sys.argv[:0] = argv0
893 raise Restart
894
895 do_restart = do_run
896
Tim Peters2344fae2001-01-15 00:50:52 +0000897 def do_return(self, arg):
898 self.set_return(self.curframe)
899 return 1
900 do_r = do_return
901
902 def do_continue(self, arg):
903 self.set_continue()
904 return 1
905 do_c = do_cont = do_continue
906
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000907 def do_jump(self, arg):
908 if self.curindex + 1 != len(self.stack):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000909 print("*** You can only jump within the bottom frame", file=self.stdout)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000910 return
911 try:
912 arg = int(arg)
913 except ValueError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000914 print("*** The 'jump' command requires a line number.", file=self.stdout)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000915 else:
916 try:
917 # Do the jump, fix up our copy of the stack, and display the
918 # new position
919 self.curframe.f_lineno = arg
920 self.stack[self.curindex] = self.stack[self.curindex][0], arg
921 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumb940e112007-01-10 16:19:56 +0000922 except ValueError as e:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000923 print('*** Jump failed:', e, file=self.stdout)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000924 do_j = do_jump
925
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000926 def do_debug(self, arg):
927 sys.settrace(None)
928 globals = self.curframe.f_globals
Benjamin Petersond23f8222009-04-05 19:13:16 +0000929 locals = self.curframe_locals
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000930 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +0000931 p.prompt = "(%s) " % self.prompt.strip()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000932 print("ENTERING RECURSIVE DEBUGGER", file=self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +0000933 sys.call_tracing(p.run, (arg, globals, locals))
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000934 print("LEAVING RECURSIVE DEBUGGER", file=self.stdout)
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000935 sys.settrace(self.trace_dispatch)
936 self.lastcmd = p.lastcmd
937
Tim Peters2344fae2001-01-15 00:50:52 +0000938 def do_quit(self, arg):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000939 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000940 self.set_quit()
941 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000942
Tim Peters2344fae2001-01-15 00:50:52 +0000943 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000944 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000945
Guido van Rossumeef26072003-01-13 21:13:55 +0000946 def do_EOF(self, arg):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000947 print(file=self.stdout)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000948 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000949 self.set_quit()
950 return 1
951
Tim Peters2344fae2001-01-15 00:50:52 +0000952 def do_args(self, arg):
Benjamin Petersond23f8222009-04-05 19:13:16 +0000953 co = self.curframe.f_code
954 dict = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000955 n = co.co_argcount
956 if co.co_flags & 4: n = n+1
957 if co.co_flags & 8: n = n+1
958 for i in range(n):
959 name = co.co_varnames[i]
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000960 print(name, '=', end=' ', file=self.stdout)
961 if name in dict: print(dict[name], file=self.stdout)
962 else: print("*** undefined ***", file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000963 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000964
Tim Peters2344fae2001-01-15 00:50:52 +0000965 def do_retval(self, arg):
Benjamin Petersond23f8222009-04-05 19:13:16 +0000966 if '__return__' in self.curframe_locals:
967 print(self.curframe_locals['__return__'], file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000968 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000969 print('*** Not yet returned!', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000970 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000971
Barry Warsaw210bd202002-11-05 22:40:20 +0000972 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000973 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +0000974 return eval(arg, self.curframe.f_globals, self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000975 except:
976 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000977 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000978 exc_type_name = t
979 else: exc_type_name = t.__name__
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000980 print('***', exc_type_name + ':', repr(v), file=self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +0000981 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000982
Barry Warsaw210bd202002-11-05 22:40:20 +0000983 def do_p(self, arg):
984 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000985 print(repr(self._getval(arg)), file=self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +0000986 except:
987 pass
Georg Brandlc9879242007-09-04 07:07:56 +0000988 # make "print" an alias of "p" since print isn't a Python statement anymore
989 do_print = do_p
Barry Warsaw210bd202002-11-05 22:40:20 +0000990
991 def do_pp(self, arg):
992 try:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000993 pprint.pprint(self._getval(arg), self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +0000994 except:
995 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000996
Tim Peters2344fae2001-01-15 00:50:52 +0000997 def do_list(self, arg):
998 self.lastcmd = 'list'
999 last = None
1000 if arg:
1001 try:
1002 x = eval(arg, {}, {})
1003 if type(x) == type(()):
1004 first, last = x
1005 first = int(first)
1006 last = int(last)
1007 if last < first:
1008 # Assume it's a count
1009 last = first + last
1010 else:
1011 first = max(1, int(x) - 5)
1012 except:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001013 print('*** Error in argument:', repr(arg), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001014 return
1015 elif self.lineno is None:
1016 first = max(1, self.curframe.f_lineno - 5)
1017 else:
1018 first = self.lineno + 1
1019 if last is None:
1020 last = first + 10
1021 filename = self.curframe.f_code.co_filename
1022 breaklist = self.get_file_breaks(filename)
1023 try:
1024 for lineno in range(first, last+1):
Georg Brandl3078df02009-05-05 09:11:31 +00001025 line = linecache.getline(filename, lineno,
1026 self.curframe.f_globals)
Tim Peters2344fae2001-01-15 00:50:52 +00001027 if not line:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001028 print('[EOF]', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001029 break
1030 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001031 s = repr(lineno).rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +00001032 if len(s) < 4: s = s + ' '
1033 if lineno in breaklist: s = s + 'B'
1034 else: s = s + ' '
1035 if lineno == self.curframe.f_lineno:
1036 s = s + '->'
Guido van Rossumceae3752007-02-09 22:16:54 +00001037 print(s + '\t' + line, end='', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001038 self.lineno = lineno
1039 except KeyboardInterrupt:
1040 pass
1041 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +00001042
Tim Peters2344fae2001-01-15 00:50:52 +00001043 def do_whatis(self, arg):
1044 try:
1045 value = eval(arg, self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +00001046 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +00001047 except:
1048 t, v = sys.exc_info()[:2]
1049 if type(t) == type(''):
1050 exc_type_name = t
1051 else: exc_type_name = t.__name__
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001052 print('***', exc_type_name + ':', repr(v), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001053 return
1054 code = None
1055 # Is it a function?
Neal Norwitz221085d2007-02-25 20:55:47 +00001056 try: code = value.__code__
Tim Peters2344fae2001-01-15 00:50:52 +00001057 except: pass
1058 if code:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001059 print('Function', code.co_name, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001060 return
1061 # Is it an instance method?
Christian Heimesff737952007-11-27 10:40:20 +00001062 try: code = value.__func__.__code__
Tim Peters2344fae2001-01-15 00:50:52 +00001063 except: pass
1064 if code:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001065 print('Method', code.co_name, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001066 return
1067 # None of the above...
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001068 print(type(value), file=self.stdout)
Guido van Rossum8e2ec561993-07-29 09:37:38 +00001069
Tim Peters2344fae2001-01-15 00:50:52 +00001070 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001071 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001072 if len(args) == 0:
Benjamin Petersonbe74a372009-09-11 21:17:13 +00001073 keys = sorted(self.aliases.keys())
Tim Peters2344fae2001-01-15 00:50:52 +00001074 for alias in keys:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001075 print("%s = %s" % (alias, self.aliases[alias]), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001076 return
Guido van Rossum08454592002-07-12 13:10:53 +00001077 if args[0] in self.aliases and len(args) == 1:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001078 print("%s = %s" % (args[0], self.aliases[args[0]]), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001079 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001080 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +00001081
Tim Peters2344fae2001-01-15 00:50:52 +00001082 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001083 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001084 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +00001085 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +00001086 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +00001087
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001088 #list of all the commands making the program resume execution.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001089 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
1090 'do_quit', 'do_jump']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001091
Tim Peters2344fae2001-01-15 00:50:52 +00001092 # Print a traceback starting at the top stack frame.
1093 # The most recently entered frame is printed last;
1094 # this is different from dbx and gdb, but consistent with
1095 # the Python interpreter's stack trace.
1096 # It is also consistent with the up/down commands (which are
1097 # compatible with dbx and gdb: up moves towards 'main()'
1098 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +00001099
Tim Peters2344fae2001-01-15 00:50:52 +00001100 def print_stack_trace(self):
1101 try:
1102 for frame_lineno in self.stack:
1103 self.print_stack_entry(frame_lineno)
1104 except KeyboardInterrupt:
1105 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001106
Tim Peters2344fae2001-01-15 00:50:52 +00001107 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
1108 frame, lineno = frame_lineno
1109 if frame is self.curframe:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001110 print('>', end=' ', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +00001111 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001112 print(' ', end=' ', file=self.stdout)
1113 print(self.format_stack_entry(frame_lineno,
1114 prompt_prefix), file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001115
Guido van Rossum921c8241992-01-10 14:54:42 +00001116
Georg Brandl02053ee2010-07-18 10:11:03 +00001117 # Help methods (derived from docstring)
Guido van Rossum921c8241992-01-10 14:54:42 +00001118
Tim Peters2344fae2001-01-15 00:50:52 +00001119 def help_help(self):
1120 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001121
Tim Peters2344fae2001-01-15 00:50:52 +00001122 def help_h(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001123 print("""h(elp)
Tim Peters2344fae2001-01-15 00:50:52 +00001124Without argument, print the list of available commands.
1125With a command name as argument, print help about that command
Georg Brandl55353ca2010-07-19 08:02:46 +00001126"help pdb" shows the full pdb documentation
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001127"help exec" gives help on the ! command""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001128
Tim Peters2344fae2001-01-15 00:50:52 +00001129 def help_where(self):
1130 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001131
Tim Peters2344fae2001-01-15 00:50:52 +00001132 def help_w(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001133 print("""w(here)
Tim Peters2344fae2001-01-15 00:50:52 +00001134Print a stack trace, with the most recent frame at the bottom.
1135An arrow indicates the "current frame", which determines the
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001136context of most commands. 'bt' is an alias for this command.""", file=self.stdout)
Guido van Rossum6bd68352001-01-20 17:57:37 +00001137
1138 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +00001139
Tim Peters2344fae2001-01-15 00:50:52 +00001140 def help_down(self):
1141 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001142
Tim Peters2344fae2001-01-15 00:50:52 +00001143 def help_d(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001144 print("""d(own)
Tim Peters2344fae2001-01-15 00:50:52 +00001145Move the current frame one level down in the stack trace
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001146(to a newer frame).""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001147
Tim Peters2344fae2001-01-15 00:50:52 +00001148 def help_up(self):
1149 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001150
Tim Peters2344fae2001-01-15 00:50:52 +00001151 def help_u(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001152 print("""u(p)
Tim Peters2344fae2001-01-15 00:50:52 +00001153Move the current frame one level up in the stack trace
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001154(to an older frame).""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001155
Tim Peters2344fae2001-01-15 00:50:52 +00001156 def help_break(self):
1157 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001158
Tim Peters2344fae2001-01-15 00:50:52 +00001159 def help_b(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001160 print("""b(reak) ([file:]lineno | function) [, condition]
Tim Peters2344fae2001-01-15 00:50:52 +00001161With a line number argument, set a break there in the current
1162file. With a function name, set a break at first executable line
1163of that function. Without argument, list all breaks. If a second
1164argument is present, it is a string specifying an expression
1165which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +00001166
Tim Peters2344fae2001-01-15 00:50:52 +00001167The line number may be prefixed with a filename and a colon,
1168to specify a breakpoint in another file (probably one that
1169hasn't been loaded yet). The file is searched for on sys.path;
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001170the .py suffix may be omitted.""", file=self.stdout)
Guido van Rossumb5699c71998-07-20 23:13:54 +00001171
Tim Peters2344fae2001-01-15 00:50:52 +00001172 def help_clear(self):
1173 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001174
Tim Peters2344fae2001-01-15 00:50:52 +00001175 def help_cl(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001176 print("cl(ear) filename:lineno", file=self.stdout)
1177 print("""cl(ear) [bpnumber [bpnumber...]]
Tim Peters2344fae2001-01-15 00:50:52 +00001178With a space separated list of breakpoint numbers, clear
1179those breakpoints. Without argument, clear all breaks (but
1180first ask confirmation). With a filename:lineno argument,
Georg Brandld348b252008-01-05 20:00:55 +00001181clear all breaks at that line in that file.""", file=self.stdout)
Guido van Rossumb5699c71998-07-20 23:13:54 +00001182
Tim Peters2344fae2001-01-15 00:50:52 +00001183 def help_tbreak(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001184 print("""tbreak same arguments as break, but breakpoint is
1185removed when first hit.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001186
Tim Peters2344fae2001-01-15 00:50:52 +00001187 def help_enable(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001188 print("""enable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +00001189Enables the breakpoints given as a space separated list of
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001190bp numbers.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001191
Tim Peters2344fae2001-01-15 00:50:52 +00001192 def help_disable(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001193 print("""disable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +00001194Disables the breakpoints given as a space separated list of
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001195bp numbers.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001196
Tim Peters2344fae2001-01-15 00:50:52 +00001197 def help_ignore(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001198 print("""ignore bpnumber count
Tim Peters2344fae2001-01-15 00:50:52 +00001199Sets the ignore count for the given breakpoint number. A breakpoint
1200becomes active when the ignore count is zero. When non-zero, the
1201count is decremented each time the breakpoint is reached and the
1202breakpoint is not disabled and any associated condition evaluates
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001203to true.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001204
Tim Peters2344fae2001-01-15 00:50:52 +00001205 def help_condition(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001206 print("""condition bpnumber str_condition
Tim Peters2344fae2001-01-15 00:50:52 +00001207str_condition is a string specifying an expression which
1208must evaluate to true before the breakpoint is honored.
1209If str_condition is absent, any existing condition is removed;
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001210i.e., the breakpoint is made unconditional.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001211
Tim Peters2344fae2001-01-15 00:50:52 +00001212 def help_step(self):
1213 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001214
Tim Peters2344fae2001-01-15 00:50:52 +00001215 def help_s(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001216 print("""s(tep)
Tim Peters2344fae2001-01-15 00:50:52 +00001217Execute the current line, stop at the first possible occasion
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001218(either in a function that is called or in the current function).""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001219
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001220 def help_until(self):
1221 self.help_unt()
1222
1223 def help_unt(self):
1224 print("""unt(il)
1225Continue execution until the line with a number greater than the current
1226one is reached or until the current frame returns""")
1227
Tim Peters2344fae2001-01-15 00:50:52 +00001228 def help_next(self):
1229 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001230
Tim Peters2344fae2001-01-15 00:50:52 +00001231 def help_n(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001232 print("""n(ext)
Tim Peters2344fae2001-01-15 00:50:52 +00001233Continue execution until the next line in the current function
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001234is reached or it returns.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001235
Tim Peters2344fae2001-01-15 00:50:52 +00001236 def help_return(self):
1237 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001238
Tim Peters2344fae2001-01-15 00:50:52 +00001239 def help_r(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001240 print("""r(eturn)
1241Continue execution until the current function returns.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001242
Tim Peters2344fae2001-01-15 00:50:52 +00001243 def help_continue(self):
1244 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001245
Tim Peters2344fae2001-01-15 00:50:52 +00001246 def help_cont(self):
1247 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001248
Tim Peters2344fae2001-01-15 00:50:52 +00001249 def help_c(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001250 print("""c(ont(inue))
1251Continue execution, only stop when a breakpoint is encountered.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001252
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001253 def help_jump(self):
1254 self.help_j()
1255
1256 def help_j(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001257 print("""j(ump) lineno
1258Set the next line that will be executed.""", file=self.stdout)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001259
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001260 def help_debug(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001261 print("""debug code
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001262Enter a recursive debugger that steps through the code argument
1263(which is an arbitrary expression or statement to be executed
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001264in the current environment).""", file=self.stdout)
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001265
Tim Peters2344fae2001-01-15 00:50:52 +00001266 def help_list(self):
1267 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001268
Tim Peters2344fae2001-01-15 00:50:52 +00001269 def help_l(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001270 print("""l(ist) [first [,last]]
Tim Peters2344fae2001-01-15 00:50:52 +00001271List source code for the current file.
1272Without arguments, list 11 lines around the current line
1273or continue the previous listing.
1274With one argument, list 11 lines starting at that line.
1275With two arguments, list the given range;
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001276if the second argument is less than the first, it is a count.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001277
Tim Peters2344fae2001-01-15 00:50:52 +00001278 def help_args(self):
1279 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001280
Tim Peters2344fae2001-01-15 00:50:52 +00001281 def help_a(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001282 print("""a(rgs)
1283Print the arguments of the current function.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001284
Tim Peters2344fae2001-01-15 00:50:52 +00001285 def help_p(self):
Georg Brandlc9879242007-09-04 07:07:56 +00001286 print("""p(rint) expression
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001287Print the value of the expression.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001288
Barry Warsaw210bd202002-11-05 22:40:20 +00001289 def help_pp(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001290 print("""pp expression
1291Pretty-print the value of the expression.""", file=self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +00001292
Tim Peters2344fae2001-01-15 00:50:52 +00001293 def help_exec(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001294 print("""(!) statement
Tim Peters2344fae2001-01-15 00:50:52 +00001295Execute the (one-line) statement in the context of
1296the current stack frame.
1297The exclamation point can be omitted unless the first word
1298of the statement resembles a debugger command.
1299To assign to a global variable you must always prefix the
1300command with a 'global' command, e.g.:
1301(Pdb) global list_options; list_options = ['-l']
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001302(Pdb)""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001303
Guido van Rossumd8faa362007-04-27 19:54:29 +00001304 def help_run(self):
1305 print("""run [args...]
1306Restart the debugged python program. If a string is supplied, it is
1307splitted with "shlex" and the result is used as the new sys.argv.
1308History, breakpoints, actions and debugger options are preserved.
1309"restart" is an alias for "run".""")
1310
1311 help_restart = help_run
1312
Tim Peters2344fae2001-01-15 00:50:52 +00001313 def help_quit(self):
1314 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001315
Tim Peters2344fae2001-01-15 00:50:52 +00001316 def help_q(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001317 print("""q(uit) or exit - Quit from the debugger.
1318The program being executed is aborted.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001319
Guido van Rossumd1c08f32002-04-15 00:48:24 +00001320 help_exit = help_q
1321
Tim Peters2344fae2001-01-15 00:50:52 +00001322 def help_whatis(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001323 print("""whatis arg
1324Prints the type of the argument.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001325
Tim Peters2344fae2001-01-15 00:50:52 +00001326 def help_EOF(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001327 print("""EOF
1328Handles the receipt of EOF as a command.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001329
Tim Peters2344fae2001-01-15 00:50:52 +00001330 def help_alias(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001331 print("""alias [name [command [parameter parameter ...] ]]
Tim Peters2344fae2001-01-15 00:50:52 +00001332Creates an alias called 'name' the executes 'command'. The command
1333must *not* be enclosed in quotes. Replaceable parameters are
1334indicated by %1, %2, and so on, while %* is replaced by all the
1335parameters. If no command is given, the current alias for name
1336is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +00001337
Tim Peters2344fae2001-01-15 00:50:52 +00001338Aliases may be nested and can contain anything that can be
1339legally typed at the pdb prompt. Note! You *can* override
1340internal pdb commands with aliases! Those internal commands
1341are then hidden until the alias is removed. Aliasing is recursively
1342applied to the first word of the command line; all other words
1343in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +00001344
Tim Peters2344fae2001-01-15 00:50:52 +00001345Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +00001346
Tim Peters2344fae2001-01-15 00:50:52 +00001347#Print instance variables (usage "pi classInst")
1348alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +00001349
Tim Peters2344fae2001-01-15 00:50:52 +00001350#Print instance variables in self
1351alias ps pi self
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001352""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001353
Tim Peters2344fae2001-01-15 00:50:52 +00001354 def help_unalias(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001355 print("""unalias name
1356Deletes the specified alias.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001357
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001358 def help_commands(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001359 print("""commands [bpnumber]
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001360(com) ...
1361(com) end
1362(Pdb)
1363
1364Specify a list of commands for breakpoint number bpnumber. The
1365commands themselves appear on the following lines. Type a line
1366containing just 'end' to terminate the commands.
1367
1368To remove all commands from a breakpoint, type commands and
1369follow it immediately with end; that is, give no commands.
1370
1371With no bpnumber argument, commands refers to the last
1372breakpoint set.
1373
1374You can use breakpoint commands to start your program up again.
1375Simply use the continue command, or step, or any other
1376command that resumes execution.
1377
1378Specifying any command resuming execution (currently continue,
1379step, next, return, jump, quit and their abbreviations) terminates
1380the command list (as if that command was immediately followed by end).
1381This is because any time you resume execution
1382(even with a simple next or step), you may encounter
1383another breakpoint--which could have its own command list, leading to
1384ambiguities about which list to execute.
1385
1386 If you use the 'silent' command in the command list, the
1387usual message about stopping at a breakpoint is not printed. This may
1388be desirable for breakpoints that are to print a specific message and
1389then continue. If none of the other commands print anything, you
1390see no sign that the breakpoint was reached.
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001391""", file=self.stdout)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001392
Tim Peters2344fae2001-01-15 00:50:52 +00001393 def help_pdb(self):
1394 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001395
Tim Peters2344fae2001-01-15 00:50:52 +00001396 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001397 """Helper function for break/clear parsing -- may be overridden.
1398
1399 lookupmodule() translates (possibly incomplete) file or module name
1400 into an absolute file name.
1401 """
1402 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001403 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001404 f = os.path.join(sys.path[0], filename)
1405 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1406 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001407 root, ext = os.path.splitext(filename)
1408 if ext == '':
1409 filename = filename + '.py'
1410 if os.path.isabs(filename):
1411 return filename
1412 for dirname in sys.path:
1413 while os.path.islink(dirname):
1414 dirname = os.readlink(dirname)
1415 fullname = os.path.join(dirname, filename)
1416 if os.path.exists(fullname):
1417 return fullname
1418 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001419
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001420 def _runscript(self, filename):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001421 # The script has to run in __main__ namespace (or imports from
1422 # __main__ will break).
1423 #
1424 # So we clear up the __main__ and set several special variables
1425 # (this gets rid of pdb's globals and cleans old variables on restarts).
1426 import __main__
1427 __main__.__dict__.clear()
1428 __main__.__dict__.update({"__name__" : "__main__",
1429 "__file__" : filename,
1430 "__builtins__": __builtins__,
1431 })
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001432
1433 # When bdb sets tracing, a number of call and line events happens
1434 # BEFORE debugger even reaches user's code (and the exact sequence of
1435 # events depends on python version). So we take special measures to
1436 # avoid stopping before we reach the main script (see user_line and
1437 # user_call for details).
1438 self._wait_for_mainpyfile = 1
1439 self.mainpyfile = self.canonic(filename)
1440 self._user_requested_quit = 0
Georg Brandld07ac642009-08-13 07:50:57 +00001441 with open(filename, "rb") as fp:
1442 statement = "exec(compile(%r, %r, 'exec'))" % \
1443 (fp.read(), self.mainpyfile)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001444 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001445
Guido van Rossum35771131992-09-08 11:59:04 +00001446# Simplified interface
1447
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001448def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001449 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001450
1451def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001452 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001453
1454def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001455 # B/W compatibility
1456 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001457
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001458def runcall(*args, **kwds):
1459 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001460
Guido van Rossumb6775db1994-08-01 11:34:53 +00001461def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001462 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001463
1464# Post-Mortem interface
1465
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001466def post_mortem(t=None):
1467 # handling the default
1468 if t is None:
1469 # sys.exc_info() returns (type, value, traceback) if an exception is
1470 # being handled, otherwise it returns None
1471 t = sys.exc_info()[2]
1472 if t is None:
1473 raise ValueError("A valid traceback must be passed if no "
1474 "exception is being handled")
1475
Tim Peters2344fae2001-01-15 00:50:52 +00001476 p = Pdb()
1477 p.reset()
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001478 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001479
1480def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001481 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001482
1483
1484# Main program for testing
1485
Guido van Rossum23efba41992-01-27 16:58:47 +00001486TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001487
Guido van Rossum921c8241992-01-10 14:54:42 +00001488def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001489 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001490
1491# print help
1492def help():
Georg Brandl02053ee2010-07-18 10:11:03 +00001493 import pydoc
1494 pydoc.pager(__doc__)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001495
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001496def main():
Christian Heimesf6cd9672008-03-26 13:45:42 +00001497 if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001498 print("usage: pdb.py scriptfile [arg] ...")
Tim Peters2344fae2001-01-15 00:50:52 +00001499 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001500
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001501 mainpyfile = sys.argv[1] # Get script filename
1502 if not os.path.exists(mainpyfile):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001503 print('Error:', mainpyfile, 'does not exist')
Tim Peters2344fae2001-01-15 00:50:52 +00001504 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001505
Tim Peters2344fae2001-01-15 00:50:52 +00001506 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001507
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001508 # Replace pdb's dir with script's dir in front of module search path.
1509 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001510
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001511 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1512 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl3078df02009-05-05 09:11:31 +00001513 # changed by the user from the command line. There is a "restart" command
1514 # which allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001515 pdb = Pdb()
1516 while 1:
1517 try:
1518 pdb._runscript(mainpyfile)
1519 if pdb._user_requested_quit:
1520 break
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001521 print("The program finished and will be restarted")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001522 except Restart:
1523 print("Restarting", mainpyfile, "with arguments:")
1524 print("\t" + " ".join(sys.argv[1:]))
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001525 except SystemExit:
1526 # In most cases SystemExit does not warrant a post-mortem session.
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001527 print("The program exited via sys.exit(). Exit status: ", end=' ')
1528 print(sys.exc_info()[1])
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001529 except:
1530 traceback.print_exc()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001531 print("Uncaught exception. Entering post mortem debugging")
1532 print("Running 'cont' or 'step' will restart the program")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001533 t = sys.exc_info()[2]
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001534 pdb.interaction(None, t)
Georg Brandl3078df02009-05-05 09:11:31 +00001535 print("Post mortem debugger finished. The " + mainpyfile +
1536 " will be restarted")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001537
1538
1539# When invoked as main program, invoke the debugger on a script
Guido van Rossumd8faa362007-04-27 19:54:29 +00001540if __name__ == '__main__':
1541 import pdb
1542 pdb.main()