blob: 7b444b113e50e051bfaf75e63ec2bfb7dca84374 [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
Georg Brandl02053ee2010-07-18 10:11:03 +000065"""
Georg Brandl0d089622010-07-30 16:00:46 +000066# NOTE: the actual command documentation is collected from docstrings of the
67# commands and is appended to __doc__ after the class has been defined.
Guido van Rossum921c8241992-01-10 14:54:42 +000068
Guido van Rossum921c8241992-01-10 14:54:42 +000069import sys
70import linecache
Guido van Rossum23efba41992-01-27 16:58:47 +000071import cmd
72import bdb
Guido van Rossumb5699c71998-07-20 23:13:54 +000073import os
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000074import re
Barry Warsaw210bd202002-11-05 22:40:20 +000075import pprint
Johannes Gijsbers25b38c82004-10-12 18:12:09 +000076import traceback
Georg Brandle59ca2a2010-07-30 17:04:28 +000077import inspect
78import types
Guido van Rossumd8faa362007-04-27 19:54:29 +000079
80
81class Restart(Exception):
82 """Causes a debugger to be restarted for the debugged python program."""
83 pass
84
Skip Montanaro352674d2001-02-07 23:14:30 +000085__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
86 "post_mortem", "help"]
87
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000088def find_function(funcname, filename):
Thomas Wouters89f507f2006-12-13 04:49:30 +000089 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
Tim Peters2344fae2001-01-15 00:50:52 +000090 try:
91 fp = open(filename)
92 except IOError:
93 return None
94 # consumer of this info expects the first line to be 1
95 lineno = 1
96 answer = None
97 while 1:
98 line = fp.readline()
99 if line == '':
100 break
101 if cre.match(line):
102 answer = funcname, filename, lineno
103 break
104 lineno = lineno + 1
105 fp.close()
106 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +0000107
108
Guido van Rossuma558e371994-11-10 22:27:35 +0000109# Interaction prompt line will separate file and call info from code
110# text using value of line_prefix string. A newline and arrow may
111# be to your liking. You can set it once pdb is imported using the
112# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +0000113# line_prefix = ': ' # Use this to get the old situation back
114line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +0000115
Guido van Rossum23efba41992-01-27 16:58:47 +0000116class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +0000117
Georg Brandl243ad662009-05-05 09:00:19 +0000118 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None):
119 bdb.Bdb.__init__(self, skip=skip)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000120 cmd.Cmd.__init__(self, completekey, stdin, stdout)
121 if stdout:
122 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000123 self.prompt = '(Pdb) '
124 self.aliases = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000125 self.mainpyfile = ''
126 self._wait_for_mainpyfile = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000127 # Try to load readline if it exists
128 try:
129 import readline
130 except ImportError:
131 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000132
Tim Peters2344fae2001-01-15 00:50:52 +0000133 # Read $HOME/.pdbrc and ./.pdbrc
134 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +0000135 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +0000136 envHome = os.environ['HOME']
137 try:
138 rcFile = open(os.path.join(envHome, ".pdbrc"))
139 except IOError:
140 pass
141 else:
142 for line in rcFile.readlines():
143 self.rcLines.append(line)
144 rcFile.close()
145 try:
146 rcFile = open(".pdbrc")
147 except IOError:
148 pass
149 else:
150 for line in rcFile.readlines():
151 self.rcLines.append(line)
152 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +0000153
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000154 self.commands = {} # associates a command list to breakpoint numbers
Benjamin Petersond23f8222009-04-05 19:13:16 +0000155 self.commands_doprompt = {} # for each bp num, tells if the prompt
156 # must be disp. after execing the cmd list
157 self.commands_silent = {} # for each bp num, tells if the stack trace
158 # must be disp. after execing the cmd list
159 self.commands_defining = False # True while in the process of defining
160 # a command list
161 self.commands_bnum = None # The breakpoint number for which we are
162 # defining a list
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000163
Tim Peters2344fae2001-01-15 00:50:52 +0000164 def reset(self):
165 bdb.Bdb.reset(self)
166 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000167
Tim Peters2344fae2001-01-15 00:50:52 +0000168 def forget(self):
169 self.lineno = None
170 self.stack = []
171 self.curindex = 0
172 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +0000173
Tim Peters2344fae2001-01-15 00:50:52 +0000174 def setup(self, f, t):
175 self.forget()
176 self.stack, self.curindex = self.get_stack(f, t)
177 self.curframe = self.stack[self.curindex][0]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000178 # The f_locals dictionary is updated from the actual frame
179 # locals whenever the .f_locals accessor is called, so we
180 # cache it here to ensure that modifications are not overwritten.
181 self.curframe_locals = self.curframe.f_locals
Georg Brandle0230912010-07-30 08:29:39 +0000182 return self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000183
Tim Peters2344fae2001-01-15 00:50:52 +0000184 # Can be executed earlier than 'setup' if desired
185 def execRcLines(self):
Georg Brandle0230912010-07-30 08:29:39 +0000186 if not self.rcLines:
187 return
188 # local copy because of recursion
189 rcLines = self.rcLines
190 rcLines.reverse()
191 # execute every line only once
192 self.rcLines = []
193 while rcLines:
194 line = rcLines.pop().strip()
195 if line and line[0] != '#':
196 if self.onecmd(line):
197 # if onecmd returns True, the command wants to exit
198 # from the interaction, save leftover rc lines
199 # to execute before next interaction
200 self.rcLines += reversed(rcLines)
201 return True
Guido van Rossum2424f851998-09-11 22:50:09 +0000202
Tim Peters280488b2002-08-23 18:19:30 +0000203 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000204
205 def user_call(self, frame, argument_list):
206 """This method is called when there is the remote possibility
207 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000208 if self._wait_for_mainpyfile:
209 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000210 if self.stop_here(frame):
Georg Brandl0d089622010-07-30 16:00:46 +0000211 self.message('--Call--')
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000212 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000213
Tim Peters2344fae2001-01-15 00:50:52 +0000214 def user_line(self, frame):
215 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000216 if self._wait_for_mainpyfile:
217 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
218 or frame.f_lineno<= 0):
219 return
220 self._wait_for_mainpyfile = 0
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000221 if self.bp_commands(frame):
222 self.interaction(frame, None)
223
Georg Brandle0230912010-07-30 08:29:39 +0000224 def bp_commands(self, frame):
Georg Brandl3078df02009-05-05 09:11:31 +0000225 """Call every command that was set for the current active breakpoint
226 (if there is one).
227
228 Returns True if the normal interaction function must be called,
229 False otherwise."""
230 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
231 if getattr(self, "currentbp", False) and \
232 self.currentbp in self.commands:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000233 currentbp = self.currentbp
234 self.currentbp = 0
235 lastcmd_back = self.lastcmd
236 self.setup(frame, None)
237 for line in self.commands[currentbp]:
238 self.onecmd(line)
239 self.lastcmd = lastcmd_back
240 if not self.commands_silent[currentbp]:
241 self.print_stack_entry(self.stack[self.curindex])
242 if self.commands_doprompt[currentbp]:
243 self.cmdloop()
244 self.forget()
245 return
246 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000247
Tim Peters2344fae2001-01-15 00:50:52 +0000248 def user_return(self, frame, return_value):
249 """This function is called when a return trap is set here."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000250 if self._wait_for_mainpyfile:
251 return
Tim Peters2344fae2001-01-15 00:50:52 +0000252 frame.f_locals['__return__'] = return_value
Georg Brandl0d089622010-07-30 16:00:46 +0000253 self.message('--Return--')
Tim Peters2344fae2001-01-15 00:50:52 +0000254 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000255
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000256 def user_exception(self, frame, exc_info):
Tim Peters2344fae2001-01-15 00:50:52 +0000257 """This function is called if an exception occurs,
258 but only if we are to stop at or just below this level."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000259 if self._wait_for_mainpyfile:
260 return
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000261 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000262 frame.f_locals['__exception__'] = exc_type, exc_value
Georg Brandl0d089622010-07-30 16:00:46 +0000263 self.message(traceback.format_exception_only(exc_type,
264 exc_value)[-1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000265 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000266
Tim Peters2344fae2001-01-15 00:50:52 +0000267 # General interaction function
268
269 def interaction(self, frame, traceback):
Georg Brandle0230912010-07-30 08:29:39 +0000270 if self.setup(frame, traceback):
271 # no interaction desired at this time (happens if .pdbrc contains
272 # a command like "continue")
273 self.forget()
274 return
Tim Peters2344fae2001-01-15 00:50:52 +0000275 self.print_stack_entry(self.stack[self.curindex])
276 self.cmdloop()
277 self.forget()
278
Benjamin Petersond23f8222009-04-05 19:13:16 +0000279 def displayhook(self, obj):
280 """Custom displayhook for the exec in default(), which prevents
281 assignment of the _ variable in the builtins.
282 """
Georg Brandl9fa2e022009-09-16 16:40:45 +0000283 # reproduce the behavior of the standard displayhook, not printing None
284 if obj is not None:
Georg Brandl0d089622010-07-30 16:00:46 +0000285 self.message(repr(obj))
Benjamin Petersond23f8222009-04-05 19:13:16 +0000286
Tim Peters2344fae2001-01-15 00:50:52 +0000287 def default(self, line):
288 if line[:1] == '!': line = line[1:]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000289 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000290 globals = self.curframe.f_globals
291 try:
292 code = compile(line + '\n', '<stdin>', 'single')
Christian Heimes679db4a2008-01-18 09:56:22 +0000293 save_stdout = sys.stdout
294 save_stdin = sys.stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000295 save_displayhook = sys.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000296 try:
297 sys.stdin = self.stdin
298 sys.stdout = self.stdout
Benjamin Petersond23f8222009-04-05 19:13:16 +0000299 sys.displayhook = self.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000300 exec(code, globals, locals)
301 finally:
302 sys.stdout = save_stdout
303 sys.stdin = save_stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000304 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000305 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000306 exc_info = sys.exc_info()[:2]
307 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000308
309 def precmd(self, line):
310 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000311 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000312 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000313 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000314 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000315 line = self.aliases[args[0]]
316 ii = 1
317 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000318 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000319 tmpArg)
320 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000321 line = line.replace("%*", ' '.join(args[1:]))
322 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000323 # split into ';;' separated commands
324 # unless it's an alias command
325 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000326 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000327 if marker >= 0:
328 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000329 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000330 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000331 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000332 return line
333
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000334 def onecmd(self, line):
335 """Interpret the argument as though it had been typed in response
336 to the prompt.
337
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000338 Checks whether this line is typed at the normal prompt or in
339 a breakpoint command list definition.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000340 """
341 if not self.commands_defining:
342 return cmd.Cmd.onecmd(self, line)
343 else:
344 return self.handle_command_def(line)
345
346 def handle_command_def(self,line):
Georg Brandl44f8bf92010-07-30 08:54:49 +0000347 """Handles one command line during command list definition."""
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000348 cmd, arg, line = self.parseline(line)
Georg Brandl44f8bf92010-07-30 08:54:49 +0000349 if not cmd:
350 return
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000351 if cmd == 'silent':
352 self.commands_silent[self.commands_bnum] = True
353 return # continue to handle other cmd def in the cmd list
354 elif cmd == 'end':
355 self.cmdqueue = []
356 return 1 # end of cmd list
357 cmdlist = self.commands[self.commands_bnum]
Georg Brandl44f8bf92010-07-30 08:54:49 +0000358 if arg:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000359 cmdlist.append(cmd+' '+arg)
360 else:
361 cmdlist.append(cmd)
362 # Determine if we must stop
363 try:
364 func = getattr(self, 'do_' + cmd)
365 except AttributeError:
366 func = self.default
Georg Brandl3078df02009-05-05 09:11:31 +0000367 # one of the resuming commands
368 if func.__name__ in self.commands_resuming:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000369 self.commands_doprompt[self.commands_bnum] = False
370 self.cmdqueue = []
371 return 1
372 return
373
Georg Brandl0d089622010-07-30 16:00:46 +0000374 # interface abstraction functions
375
376 def message(self, msg):
377 print(msg, file=self.stdout)
378
379 def error(self, msg):
380 print('***', msg, file=self.stdout)
381
Tim Peters2344fae2001-01-15 00:50:52 +0000382 # Command definitions, called by cmdloop()
383 # The argument is the remaining string on the command line
384 # Return true to exit from the command loop
385
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000386 def do_commands(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000387 """commands [bpnumber]
388 (com) ...
389 (com) end
390 (Pdb)
Georg Brandl3078df02009-05-05 09:11:31 +0000391
Georg Brandl0d089622010-07-30 16:00:46 +0000392 Specify a list of commands for breakpoint number bpnumber.
393 The commands themselves are entered on the following lines.
394 Type a line containing just 'end' to terminate the commands.
395 The commands are executed when the breakpoint is hit.
396
397 To remove all commands from a breakpoint, type commands and
398 follow it immediately with end; that is, give no commands.
399
400 With no bpnumber argument, commands refers to the last
401 breakpoint set.
402
403 You can use breakpoint commands to start your program up
404 again. Simply use the continue command, or step, or any other
405 command that resumes execution.
406
407 Specifying any command resuming execution (currently continue,
408 step, next, return, jump, quit and their abbreviations)
409 terminates the command list (as if that command was
410 immediately followed by end). This is because any time you
411 resume execution (even with a simple next or step), you may
412 encounter another breakpoint -- which could have its own
413 command list, leading to ambiguities about which list to
414 execute.
415
416 If you use the 'silent' command in the command list, the usual
417 message about stopping at a breakpoint is not printed. This
418 may be desirable for breakpoints that are to print a specific
419 message and then continue. If none of the other commands
420 print anything, you will see no sign that the breakpoint was
421 reached.
422 """
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000423 if not arg:
Georg Brandl7410dd12010-07-30 12:01:20 +0000424 bnum = len(bdb.Breakpoint.bpbynumber) - 1
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000425 else:
426 try:
427 bnum = int(arg)
428 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000429 self.error("Usage: commands [bnum]\n ...\n end")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000430 return
431 self.commands_bnum = bnum
432 self.commands[bnum] = []
433 self.commands_doprompt[bnum] = True
434 self.commands_silent[bnum] = False
435 prompt_back = self.prompt
436 self.prompt = '(com) '
437 self.commands_defining = True
Georg Brandl44f8bf92010-07-30 08:54:49 +0000438 try:
439 self.cmdloop()
440 finally:
441 self.commands_defining = False
442 self.prompt = prompt_back
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000443
Tim Peters2344fae2001-01-15 00:50:52 +0000444 def do_break(self, arg, temporary = 0):
Georg Brandl0d089622010-07-30 16:00:46 +0000445 """b(reak) [ ([filename:]lineno | function) [, condition] ]
446 Without argument, list all breaks.
447
448 With a line number argument, set a break at this line in the
449 current file. With a function name, set a break at the first
450 executable line of that function. If a second argument is
451 present, it is a string specifying an expression which must
452 evaluate to true before the breakpoint is honored.
453
454 The line number may be prefixed with a filename and a colon,
455 to specify a breakpoint in another file (probably one that
456 hasn't been loaded yet). The file is searched for on
457 sys.path; the .py suffix may be omitted.
458 """
Tim Peters2344fae2001-01-15 00:50:52 +0000459 if not arg:
460 if self.breaks: # There's at least one
Georg Brandl0d089622010-07-30 16:00:46 +0000461 self.message("Num Type Disp Enb Where")
Tim Peters2344fae2001-01-15 00:50:52 +0000462 for bp in bdb.Breakpoint.bpbynumber:
463 if bp:
Georg Brandl0d089622010-07-30 16:00:46 +0000464 self.message(bp.bpformat())
Tim Peters2344fae2001-01-15 00:50:52 +0000465 return
466 # parse arguments; comma has lowest precedence
467 # and cannot occur in filename
468 filename = None
469 lineno = None
470 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000471 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000472 if comma > 0:
473 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000474 cond = arg[comma+1:].lstrip()
475 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000476 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000477 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000478 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000479 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000480 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000481 f = self.lookupmodule(filename)
482 if not f:
Georg Brandl0d089622010-07-30 16:00:46 +0000483 self.error('%r not found from sys.path' % filename)
Tim Peters2344fae2001-01-15 00:50:52 +0000484 return
485 else:
486 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000487 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000488 try:
489 lineno = int(arg)
Guido van Rossumb940e112007-01-10 16:19:56 +0000490 except ValueError as msg:
Georg Brandl0d089622010-07-30 16:00:46 +0000491 self.error('Bad lineno: %s' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000492 return
493 else:
494 # no colon; can be lineno or function
495 try:
496 lineno = int(arg)
497 except ValueError:
498 try:
499 func = eval(arg,
500 self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +0000501 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000502 except:
503 func = arg
504 try:
Christian Heimesff737952007-11-27 10:40:20 +0000505 if hasattr(func, '__func__'):
506 func = func.__func__
Neal Norwitz221085d2007-02-25 20:55:47 +0000507 code = func.__code__
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000508 #use co_name to identify the bkpt (function names
509 #could be aliased, but co_name is invariant)
510 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000511 lineno = code.co_firstlineno
512 filename = code.co_filename
513 except:
514 # last thing to try
515 (ok, filename, ln) = self.lineinfo(arg)
516 if not ok:
Georg Brandl0d089622010-07-30 16:00:46 +0000517 self.error('The specified object %r is not a function '
518 'or was not found along sys.path.' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000519 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000520 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000521 lineno = int(ln)
522 if not filename:
523 filename = self.defaultFile()
524 # Check for reasonable breakpoint
525 line = self.checkline(filename, lineno)
526 if line:
527 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000528 err = self.set_break(filename, line, temporary, cond, funcname)
Georg Brandl0d089622010-07-30 16:00:46 +0000529 if err:
530 self.error(err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000531 else:
532 bp = self.get_breaks(filename, line)[-1]
Georg Brandl0d089622010-07-30 16:00:46 +0000533 self.message("Breakpoint %d at %s:%d" %
534 (bp.number, bp.file, bp.line))
Tim Peters2344fae2001-01-15 00:50:52 +0000535
536 # To be overridden in derived debuggers
537 def defaultFile(self):
538 """Produce a reasonable default."""
539 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000540 if filename == '<string>' and self.mainpyfile:
541 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000542 return filename
543
544 do_b = do_break
545
546 def do_tbreak(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000547 """tbreak [ ([filename:]lineno | function) [, condition] ]
548 Same arguments as break, but sets a temporary breakpoint: it
549 is automatically deleted when first hit.
550 """
Tim Peters2344fae2001-01-15 00:50:52 +0000551 self.do_break(arg, 1)
552
553 def lineinfo(self, identifier):
554 failed = (None, None, None)
555 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000556 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000557 if len(idstring) == 1:
558 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000559 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000560 elif len(idstring) == 3:
561 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000562 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000563 else:
564 return failed
565 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000566 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000567 # Protection for derived debuggers
568 if parts[0] == 'self':
569 del parts[0]
570 if len(parts) == 0:
571 return failed
572 # Best first guess at file to look at
573 fname = self.defaultFile()
574 if len(parts) == 1:
575 item = parts[0]
576 else:
577 # More than one part.
578 # First is module, second is method/class
579 f = self.lookupmodule(parts[0])
580 if f:
581 fname = f
582 item = parts[1]
583 answer = find_function(item, fname)
584 return answer or failed
585
586 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000587 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000588
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000589 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
590 line or EOF). Warning: testing is not comprehensive.
591 """
Georg Brandl1e30bd32010-07-30 07:21:26 +0000592 # this method should be callable before starting debugging, so default
593 # to "no globals" if there is no current frame
594 globs = self.curframe.f_globals if hasattr(self, 'curframe') else None
595 line = linecache.getline(filename, lineno, globs)
Tim Peters2344fae2001-01-15 00:50:52 +0000596 if not line:
Georg Brandl0d089622010-07-30 16:00:46 +0000597 self.message('End of file')
Tim Peters2344fae2001-01-15 00:50:52 +0000598 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000599 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000600 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000601 if (not line or (line[0] == '#') or
602 (line[:3] == '"""') or line[:3] == "'''"):
Georg Brandl0d089622010-07-30 16:00:46 +0000603 self.error('Blank or comment')
Tim Peters2344fae2001-01-15 00:50:52 +0000604 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000605 return lineno
606
607 def do_enable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000608 """enable bpnumber [bpnumber ...]
609 Enables the breakpoints given as a space separated list of
610 breakpoint numbers.
611 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000612 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000613 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000614 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000615 bp = self.get_bpbynumber(i)
616 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000617 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000618 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000619 bp.enable()
Georg Brandl0d089622010-07-30 16:00:46 +0000620 self.message('Enabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000621
622 def do_disable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000623 """disable bpnumber [bpnumber ...]
624 Disables the breakpoints given as a space separated list of
625 breakpoint numbers. Disabling a breakpoint means it cannot
626 cause the program to stop execution, but unlike clearing a
627 breakpoint, it remains in the list of breakpoints and can be
628 (re-)enabled.
629 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000630 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000631 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000632 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000633 bp = self.get_bpbynumber(i)
634 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000635 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000636 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000637 bp.disable()
Georg Brandl0d089622010-07-30 16:00:46 +0000638 self.message('Disabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000639
640 def do_condition(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000641 """condition bpnumber [condition]
642 Set a new condition for the breakpoint, an expression which
643 must evaluate to true before the breakpoint is honored. If
644 condition is absent, any existing condition is removed; i.e.,
645 the breakpoint is made unconditional.
646 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000647 args = arg.split(' ', 1)
Thomas Woutersb2137042007-02-01 18:02:27 +0000648 try:
Tim Peters2344fae2001-01-15 00:50:52 +0000649 cond = args[1]
Georg Brandl7410dd12010-07-30 12:01:20 +0000650 except IndexError:
Tim Peters2344fae2001-01-15 00:50:52 +0000651 cond = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000652 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000653 bp = self.get_bpbynumber(args[0].strip())
654 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000655 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000656 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000657 bp.cond = cond
658 if not cond:
Georg Brandl0d089622010-07-30 16:00:46 +0000659 self.message('Breakpoint %d is now unconditional.' % bp.number)
Georg Brandl7410dd12010-07-30 12:01:20 +0000660 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000661 self.message('New condition set for breakpoint %d.' % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000662
Georg Brandl7410dd12010-07-30 12:01:20 +0000663 def do_ignore(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000664 """ignore bpnumber [count]
665 Set the ignore count for the given breakpoint number. If
666 count is omitted, the ignore count is set to 0. A breakpoint
667 becomes active when the ignore count is zero. When non-zero,
668 the count is decremented each time the breakpoint is reached
669 and the breakpoint is not disabled and any associated
670 condition evaluates to true.
671 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000672 args = arg.split()
Thomas Woutersb2137042007-02-01 18:02:27 +0000673 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000674 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000675 except:
676 count = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +0000677 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000678 bp = self.get_bpbynumber(args[0].strip())
679 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000680 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000681 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000682 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000683 if count > 0:
Guido van Rossum08454592002-07-12 13:10:53 +0000684 if count > 1:
Georg Brandl0d089622010-07-30 16:00:46 +0000685 countstr = '%d crossings' % count
Tim Peters2344fae2001-01-15 00:50:52 +0000686 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000687 countstr = '1 crossing'
688 self.message('Will ignore next %s of breakpoint %d.' %
689 (countstr, bp.number))
Tim Peters2344fae2001-01-15 00:50:52 +0000690 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000691 self.message('Will stop next time breakpoint %d is reached.'
692 % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000693
694 def do_clear(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000695 """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]]
696 With a space separated list of breakpoint numbers, clear
697 those breakpoints. Without argument, clear all breaks (but
698 first ask confirmation). With a filename:lineno argument,
699 clear all breaks at that line in that file.
700 """
Tim Peters2344fae2001-01-15 00:50:52 +0000701 if not arg:
702 try:
Guido van Rossumc5b6ab02007-05-27 09:19:52 +0000703 reply = input('Clear all breaks? ')
Tim Peters2344fae2001-01-15 00:50:52 +0000704 except EOFError:
705 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000706 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000707 if reply in ('y', 'yes'):
Georg Brandl7410dd12010-07-30 12:01:20 +0000708 bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp]
Tim Peters2344fae2001-01-15 00:50:52 +0000709 self.clear_all_breaks()
Georg Brandl7410dd12010-07-30 12:01:20 +0000710 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000711 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000712 return
713 if ':' in arg:
714 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000715 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000716 filename = arg[:i]
717 arg = arg[i+1:]
718 try:
719 lineno = int(arg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000720 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000721 err = "Invalid line number (%s)" % arg
722 else:
Georg Brandl7410dd12010-07-30 12:01:20 +0000723 bplist = self.get_breaks(filename, lineno)
Tim Peters2344fae2001-01-15 00:50:52 +0000724 err = self.clear_break(filename, lineno)
Georg Brandl7410dd12010-07-30 12:01:20 +0000725 if err:
Georg Brandl0d089622010-07-30 16:00:46 +0000726 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000727 else:
728 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000729 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000730 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000731 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000732 for i in numberlist:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000733 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000734 bp = self.get_bpbynumber(i)
735 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000736 self.error(err)
Tim Peters2344fae2001-01-15 00:50:52 +0000737 else:
Georg Brandl7410dd12010-07-30 12:01:20 +0000738 self.clear_break(bp.file, bp.line)
Georg Brandl0d089622010-07-30 16:00:46 +0000739 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000740 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
741
742 def do_where(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000743 """w(here)
744 Print a stack trace, with the most recent frame at the bottom.
745 An arrow indicates the "current frame", which determines the
746 context of most commands. 'bt' is an alias for this command.
747 """
Tim Peters2344fae2001-01-15 00:50:52 +0000748 self.print_stack_trace()
749 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000750 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000751
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000752 def _select_frame(self, number):
753 assert 0 <= number < len(self.stack)
754 self.curindex = number
755 self.curframe = self.stack[self.curindex][0]
756 self.curframe_locals = self.curframe.f_locals
757 self.print_stack_entry(self.stack[self.curindex])
758 self.lineno = None
759
Tim Peters2344fae2001-01-15 00:50:52 +0000760 def do_up(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000761 """u(p) [count]
762 Move the current frame count (default one) levels up in the
763 stack trace (to an older frame).
764 """
Tim Peters2344fae2001-01-15 00:50:52 +0000765 if self.curindex == 0:
Georg Brandl0d089622010-07-30 16:00:46 +0000766 self.error('Oldest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000767 return
768 try:
769 count = int(arg or 1)
770 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000771 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000772 return
773 if count < 0:
774 newframe = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000775 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000776 newframe = max(0, self.curindex - count)
777 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000778 do_u = do_up
779
780 def do_down(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000781 """d(own) [count]
782 Move the current frame count (default one) levels down in the
783 stack trace (to a newer frame).
784 """
Tim Peters2344fae2001-01-15 00:50:52 +0000785 if self.curindex + 1 == len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +0000786 self.error('Newest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000787 return
788 try:
789 count = int(arg or 1)
790 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000791 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000792 return
793 if count < 0:
794 newframe = len(self.stack) - 1
Tim Peters2344fae2001-01-15 00:50:52 +0000795 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000796 newframe = min(len(self.stack) - 1, self.curindex + count)
797 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000798 do_d = do_down
799
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000800 def do_until(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000801 """unt(il) [lineno]
802 Without argument, continue execution until the line with a
803 number greater than the current one is reached. With a line
804 number, continue execution until a line with a number greater
805 or equal to that is reached. In both cases, also stop when
806 the current frame returns.
807 """
Georg Brandl2dfec552010-07-30 08:43:32 +0000808 if arg:
809 try:
810 lineno = int(arg)
811 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000812 self.error('Error in argument: %r' % arg)
Georg Brandl2dfec552010-07-30 08:43:32 +0000813 return
814 if lineno <= self.curframe.f_lineno:
Georg Brandl0d089622010-07-30 16:00:46 +0000815 self.error('"until" line number is smaller than current '
816 'line number')
Georg Brandl2dfec552010-07-30 08:43:32 +0000817 return
818 else:
819 lineno = None
820 self.set_until(self.curframe, lineno)
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000821 return 1
822 do_unt = do_until
823
Tim Peters2344fae2001-01-15 00:50:52 +0000824 def do_step(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000825 """s(tep)
826 Execute the current line, stop at the first possible occasion
827 (either in a function that is called or in the current
828 function).
829 """
Tim Peters2344fae2001-01-15 00:50:52 +0000830 self.set_step()
831 return 1
832 do_s = do_step
833
834 def do_next(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000835 """n(ext)
836 Continue execution until the next line in the current function
837 is reached or it returns.
838 """
Tim Peters2344fae2001-01-15 00:50:52 +0000839 self.set_next(self.curframe)
840 return 1
841 do_n = do_next
842
Guido van Rossumd8faa362007-04-27 19:54:29 +0000843 def do_run(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000844 """run [args...]
845 Restart the debugged python program. If a string is supplied
846 it is splitted with "shlex", and the result is used as the new
847 sys.argv. History, breakpoints, actions and debugger options
848 are preserved. "restart" is an alias for "run".
849 """
Guido van Rossumd8faa362007-04-27 19:54:29 +0000850 if arg:
851 import shlex
852 argv0 = sys.argv[0:1]
853 sys.argv = shlex.split(arg)
854 sys.argv[:0] = argv0
Georg Brandl0d089622010-07-30 16:00:46 +0000855 # this is caught in the main debugger loop
Guido van Rossumd8faa362007-04-27 19:54:29 +0000856 raise Restart
857
858 do_restart = do_run
859
Tim Peters2344fae2001-01-15 00:50:52 +0000860 def do_return(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000861 """r(eturn)
862 Continue execution until the current function returns.
863 """
Tim Peters2344fae2001-01-15 00:50:52 +0000864 self.set_return(self.curframe)
865 return 1
866 do_r = do_return
867
868 def do_continue(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000869 """c(ont(inue))
870 Continue execution, only stop when a breakpoint is encountered.
871 """
Tim Peters2344fae2001-01-15 00:50:52 +0000872 self.set_continue()
873 return 1
874 do_c = do_cont = do_continue
875
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000876 def do_jump(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000877 """j(ump) lineno
878 Set the next line that will be executed. Only available in
879 the bottom-most frame. This lets you jump back and execute
880 code again, or jump forward to skip code that you don't want
881 to run.
882
883 It should be noted that not all jumps are allowed -- for
884 instance it is not possible to jump into the middle of a
885 for loop or out of a finally clause.
886 """
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000887 if self.curindex + 1 != len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +0000888 self.error('You can only jump within the bottom frame')
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000889 return
890 try:
891 arg = int(arg)
892 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000893 self.error("The 'jump' command requires a line number")
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000894 else:
895 try:
896 # Do the jump, fix up our copy of the stack, and display the
897 # new position
898 self.curframe.f_lineno = arg
899 self.stack[self.curindex] = self.stack[self.curindex][0], arg
900 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumb940e112007-01-10 16:19:56 +0000901 except ValueError as e:
Georg Brandl0d089622010-07-30 16:00:46 +0000902 self.error('Jump failed: %s' % e)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000903 do_j = do_jump
904
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000905 def do_debug(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000906 """debug code
907 Enter a recursive debugger that steps through the code
908 argument (which is an arbitrary expression or statement to be
909 executed in the current environment).
910 """
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000911 sys.settrace(None)
912 globals = self.curframe.f_globals
Benjamin Petersond23f8222009-04-05 19:13:16 +0000913 locals = self.curframe_locals
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000914 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +0000915 p.prompt = "(%s) " % self.prompt.strip()
Georg Brandl0d089622010-07-30 16:00:46 +0000916 self.message("ENTERING RECURSIVE DEBUGGER")
Guido van Rossumed538d82003-04-09 19:36:34 +0000917 sys.call_tracing(p.run, (arg, globals, locals))
Georg Brandl0d089622010-07-30 16:00:46 +0000918 self.message("LEAVING RECURSIVE DEBUGGER")
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000919 sys.settrace(self.trace_dispatch)
920 self.lastcmd = p.lastcmd
921
Tim Peters2344fae2001-01-15 00:50:52 +0000922 def do_quit(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000923 """q(uit)\nexit
924 Quit from the debugger. The program being executed is aborted.
925 """
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000926 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000927 self.set_quit()
928 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000929
Tim Peters2344fae2001-01-15 00:50:52 +0000930 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000931 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000932
Guido van Rossumeef26072003-01-13 21:13:55 +0000933 def do_EOF(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000934 """EOF
935 Handles the receipt of EOF as a command.
936 """
937 self.message('')
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000938 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000939 self.set_quit()
940 return 1
941
Tim Peters2344fae2001-01-15 00:50:52 +0000942 def do_args(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000943 """a(rgs)
944 Print the argument list of the current function.
945 """
Benjamin Petersond23f8222009-04-05 19:13:16 +0000946 co = self.curframe.f_code
947 dict = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000948 n = co.co_argcount
949 if co.co_flags & 4: n = n+1
950 if co.co_flags & 8: n = n+1
951 for i in range(n):
952 name = co.co_varnames[i]
Georg Brandl0d089622010-07-30 16:00:46 +0000953 if name in dict:
954 self.message('%s = %r' % (name, dict[name]))
955 else:
956 self.message('%s = *** undefined ***' % (name,))
Tim Peters2344fae2001-01-15 00:50:52 +0000957 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000958
Tim Peters2344fae2001-01-15 00:50:52 +0000959 def do_retval(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000960 """retval
961 Print the return value for the last return of a function.
962 """
Benjamin Petersond23f8222009-04-05 19:13:16 +0000963 if '__return__' in self.curframe_locals:
Georg Brandl0d089622010-07-30 16:00:46 +0000964 self.message(repr(self.curframe_locals['__return__']))
Tim Peters2344fae2001-01-15 00:50:52 +0000965 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000966 self.error('Not yet returned!')
Tim Peters2344fae2001-01-15 00:50:52 +0000967 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000968
Barry Warsaw210bd202002-11-05 22:40:20 +0000969 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000970 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +0000971 return eval(arg, self.curframe.f_globals, self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000972 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000973 exc_info = sys.exc_info()[:2]
974 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Barry Warsaw210bd202002-11-05 22:40:20 +0000975 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000976
Barry Warsaw210bd202002-11-05 22:40:20 +0000977 def do_p(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000978 """p(rint) expression
979 Print the value of the expression.
980 """
Barry Warsaw210bd202002-11-05 22:40:20 +0000981 try:
Georg Brandl0d089622010-07-30 16:00:46 +0000982 self.message(repr(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +0000983 except:
984 pass
Georg Brandlc9879242007-09-04 07:07:56 +0000985 # make "print" an alias of "p" since print isn't a Python statement anymore
986 do_print = do_p
Barry Warsaw210bd202002-11-05 22:40:20 +0000987
988 def do_pp(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000989 """pp expression
990 Pretty-print the value of the expression.
991 """
Barry Warsaw210bd202002-11-05 22:40:20 +0000992 try:
Georg Brandl0d089622010-07-30 16:00:46 +0000993 self.message(pprint.pformat(self._getval(arg)))
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):
Georg Brandl0d089622010-07-30 16:00:46 +0000998 """l(ist) [first [,last] | .]
999 List source code for the current file.
1000 Without arguments, list 11 lines around the current line
1001 or continue the previous listing.
1002 With . as argument, list 11 lines around the current line.
1003 With one argument, list 11 lines starting at that line.
1004 With two arguments, list the given range;
1005 if the second argument is less than the first, it is a count.
1006 """
Tim Peters2344fae2001-01-15 00:50:52 +00001007 self.lastcmd = 'list'
1008 last = None
Georg Brandla91a94b2010-07-30 07:14:01 +00001009 if arg and arg != '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001010 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001011 if ',' in arg:
1012 first, last = arg.split(',')
1013 first = int(first.strip())
1014 last = int(last.strip())
Tim Peters2344fae2001-01-15 00:50:52 +00001015 if last < first:
Georg Brandl0d089622010-07-30 16:00:46 +00001016 # assume it's a count
Tim Peters2344fae2001-01-15 00:50:52 +00001017 last = first + last
1018 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001019 first = int(arg.strip())
1020 first = max(1, first - 5)
1021 except ValueError:
1022 self.error('Error in argument: %r' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001023 return
Georg Brandla91a94b2010-07-30 07:14:01 +00001024 elif self.lineno is None or arg == '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001025 first = max(1, self.curframe.f_lineno - 5)
1026 else:
1027 first = self.lineno + 1
1028 if last is None:
1029 last = first + 10
1030 filename = self.curframe.f_code.co_filename
1031 breaklist = self.get_file_breaks(filename)
1032 try:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001033 # XXX add tb_lineno feature
1034 lines = linecache.getlines(filename, self.curframe.f_globals)
1035 self._print_lines(lines[first-1:last], first, breaklist,
1036 self.curframe.f_lineno, -1)
1037 self.lineno = min(last, len(lines))
1038 if len(lines) < last:
1039 self.message('[EOF]')
Tim Peters2344fae2001-01-15 00:50:52 +00001040 except KeyboardInterrupt:
1041 pass
1042 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +00001043
Georg Brandle59ca2a2010-07-30 17:04:28 +00001044 def do_longlist(self, arg):
1045 """longlist | ll
1046 List the whole source code for the current function or frame.
1047 """
1048 filename = self.curframe.f_code.co_filename
1049 breaklist = self.get_file_breaks(filename)
1050 try:
1051 lines, lineno = inspect.getsourcelines(self.curframe)
1052 except IOError as err:
1053 self.error(err)
1054 return
1055 self._print_lines(lines, lineno, breaklist, self.curframe.f_lineno, -1)
1056 do_ll = do_longlist
1057
1058 def do_source(self, arg):
1059 """source expression
1060 Try to get source code for the given object and display it.
1061 """
1062 try:
1063 obj = self._getval(arg)
1064 except:
1065 return
1066 try:
1067 lines, lineno = inspect.getsourcelines(obj)
1068 except (IOError, TypeError) as err:
1069 self.error(err)
1070 return
1071 self._print_lines(lines, lineno, [], -1, -1)
1072
1073 def _print_lines(self, lines, start, breaks, current, special):
1074 """Print a range of lines."""
1075 for lineno, line in enumerate(lines, start):
1076 s = str(lineno).rjust(3)
1077 if len(s) < 4:
1078 s += ' '
1079 if lineno in breaks:
1080 s += 'B'
1081 else:
1082 s += ' '
1083 if lineno == current:
1084 s += '->'
1085 elif lineno == special:
1086 s += '>>'
1087 self.message(s + '\t' + line.rstrip())
1088
Tim Peters2344fae2001-01-15 00:50:52 +00001089 def do_whatis(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001090 """whatis arg
1091 Print the type of the argument.
1092 """
Tim Peters2344fae2001-01-15 00:50:52 +00001093 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001094 value = self._getval(arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001095 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001096 # _getval() already printed the error
Tim Peters2344fae2001-01-15 00:50:52 +00001097 return
1098 code = None
1099 # Is it a function?
Georg Brandl0d089622010-07-30 16:00:46 +00001100 try:
1101 code = value.__code__
1102 except Exception:
1103 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001104 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001105 self.message('Function %s' % code.co_name)
Tim Peters2344fae2001-01-15 00:50:52 +00001106 return
1107 # Is it an instance method?
Georg Brandl0d089622010-07-30 16:00:46 +00001108 try:
1109 code = value.__func__.__code__
1110 except Exception:
1111 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001112 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001113 self.message('Method %s' % code.co_name)
1114 return
1115 # Is it a class?
1116 if value.__class__ is type:
1117 self.message('Class %s.%s' % (value.__module__, value.__name__))
Tim Peters2344fae2001-01-15 00:50:52 +00001118 return
1119 # None of the above...
Georg Brandl0d089622010-07-30 16:00:46 +00001120 self.message(type(value))
Guido van Rossum8e2ec561993-07-29 09:37:38 +00001121
Tim Peters2344fae2001-01-15 00:50:52 +00001122 def do_alias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001123 """alias [name [command [parameter parameter ...] ]]
1124 Create an alias called 'name' that executes 'command'. The
1125 command must *not* be enclosed in quotes. Replaceable
1126 parameters can be indicated by %1, %2, and so on, while %* is
1127 replaced by all the parameters. If no command is given, the
1128 current alias for name is shown. If no name is given, all
1129 aliases are listed.
1130
1131 Aliases may be nested and can contain anything that can be
1132 legally typed at the pdb prompt. Note! You *can* override
1133 internal pdb commands with aliases! Those internal commands
1134 are then hidden until the alias is removed. Aliasing is
1135 recursively applied to the first word of the command line; all
1136 other words in the line are left alone.
1137
1138 As an example, here are two useful aliases (especially when
1139 placed in the .pdbrc file):
1140
1141 # Print instance variables (usage "pi classInst")
1142 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
1143 # Print instance variables in self
1144 alias ps pi self
1145 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001146 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001147 if len(args) == 0:
Benjamin Petersonbe74a372009-09-11 21:17:13 +00001148 keys = sorted(self.aliases.keys())
Tim Peters2344fae2001-01-15 00:50:52 +00001149 for alias in keys:
Georg Brandl0d089622010-07-30 16:00:46 +00001150 self.message("%s = %s" % (alias, self.aliases[alias]))
Tim Peters2344fae2001-01-15 00:50:52 +00001151 return
Guido van Rossum08454592002-07-12 13:10:53 +00001152 if args[0] in self.aliases and len(args) == 1:
Georg Brandl0d089622010-07-30 16:00:46 +00001153 self.message("%s = %s" % (args[0], self.aliases[args[0]]))
Tim Peters2344fae2001-01-15 00:50:52 +00001154 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001155 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +00001156
Tim Peters2344fae2001-01-15 00:50:52 +00001157 def do_unalias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001158 """unalias name
1159 Delete the specified alias.
1160 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001161 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001162 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +00001163 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +00001164 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +00001165
Georg Brandl0d089622010-07-30 16:00:46 +00001166 # List of all the commands making the program resume execution.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001167 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
1168 'do_quit', 'do_jump']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001169
Tim Peters2344fae2001-01-15 00:50:52 +00001170 # Print a traceback starting at the top stack frame.
1171 # The most recently entered frame is printed last;
1172 # this is different from dbx and gdb, but consistent with
1173 # the Python interpreter's stack trace.
1174 # It is also consistent with the up/down commands (which are
1175 # compatible with dbx and gdb: up moves towards 'main()'
1176 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +00001177
Tim Peters2344fae2001-01-15 00:50:52 +00001178 def print_stack_trace(self):
1179 try:
1180 for frame_lineno in self.stack:
1181 self.print_stack_entry(frame_lineno)
1182 except KeyboardInterrupt:
1183 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001184
Tim Peters2344fae2001-01-15 00:50:52 +00001185 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
1186 frame, lineno = frame_lineno
1187 if frame is self.curframe:
Georg Brandl0d089622010-07-30 16:00:46 +00001188 prefix = '> '
Tim Peters2344fae2001-01-15 00:50:52 +00001189 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001190 prefix = ' '
1191 self.message(prefix +
1192 self.format_stack_entry(frame_lineno, prompt_prefix))
Guido van Rossum2424f851998-09-11 22:50:09 +00001193
Georg Brandl0d089622010-07-30 16:00:46 +00001194 # Provide help
Guido van Rossum921c8241992-01-10 14:54:42 +00001195
Georg Brandl0d089622010-07-30 16:00:46 +00001196 def do_help(self, arg):
1197 """h(elp)
1198 Without argument, print the list of available commands.
1199 With a command name as argument, print help about that command.
1200 "help pdb" shows the full pdb documentation.
1201 "help exec" gives help on the ! command.
1202 """
1203 if not arg:
1204 return cmd.Cmd.do_help(self, arg)
1205 try:
1206 try:
1207 topic = getattr(self, 'help_' + arg)
1208 return topic()
1209 except AttributeError:
1210 command = getattr(self, 'do_' + arg)
1211 except AttributeError:
1212 self.error('No help for %r' % arg)
1213 else:
1214 self.message(command.__doc__.rstrip())
Guido van Rossum921c8241992-01-10 14:54:42 +00001215
Georg Brandl0d089622010-07-30 16:00:46 +00001216 do_h = do_help
Barry Warsaw210bd202002-11-05 22:40:20 +00001217
Tim Peters2344fae2001-01-15 00:50:52 +00001218 def help_exec(self):
Georg Brandl0d089622010-07-30 16:00:46 +00001219 """(!) statement
1220 Execute the (one-line) statement in the context of the current
1221 stack frame. The exclamation point can be omitted unless the
1222 first word of the statement resembles a debugger command. To
1223 assign to a global variable you must always prefix the command
1224 with a 'global' command, e.g.:
1225 (Pdb) global list_options; list_options = ['-l']
1226 (Pdb)
1227 """
1228 self.message(self.help_exec.__doc__.strip())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001229
Tim Peters2344fae2001-01-15 00:50:52 +00001230 def help_pdb(self):
1231 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001232
Georg Brandl0d089622010-07-30 16:00:46 +00001233 # other helper functions
1234
Tim Peters2344fae2001-01-15 00:50:52 +00001235 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001236 """Helper function for break/clear parsing -- may be overridden.
1237
1238 lookupmodule() translates (possibly incomplete) file or module name
1239 into an absolute file name.
1240 """
1241 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001242 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001243 f = os.path.join(sys.path[0], filename)
1244 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1245 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001246 root, ext = os.path.splitext(filename)
1247 if ext == '':
1248 filename = filename + '.py'
1249 if os.path.isabs(filename):
1250 return filename
1251 for dirname in sys.path:
1252 while os.path.islink(dirname):
1253 dirname = os.readlink(dirname)
1254 fullname = os.path.join(dirname, filename)
1255 if os.path.exists(fullname):
1256 return fullname
1257 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001258
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001259 def _runscript(self, filename):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001260 # The script has to run in __main__ namespace (or imports from
1261 # __main__ will break).
1262 #
1263 # So we clear up the __main__ and set several special variables
1264 # (this gets rid of pdb's globals and cleans old variables on restarts).
1265 import __main__
1266 __main__.__dict__.clear()
1267 __main__.__dict__.update({"__name__" : "__main__",
1268 "__file__" : filename,
1269 "__builtins__": __builtins__,
1270 })
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001271
1272 # When bdb sets tracing, a number of call and line events happens
1273 # BEFORE debugger even reaches user's code (and the exact sequence of
1274 # events depends on python version). So we take special measures to
1275 # avoid stopping before we reach the main script (see user_line and
1276 # user_call for details).
1277 self._wait_for_mainpyfile = 1
1278 self.mainpyfile = self.canonic(filename)
1279 self._user_requested_quit = 0
Georg Brandld07ac642009-08-13 07:50:57 +00001280 with open(filename, "rb") as fp:
1281 statement = "exec(compile(%r, %r, 'exec'))" % \
1282 (fp.read(), self.mainpyfile)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001283 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001284
Georg Brandl0d089622010-07-30 16:00:46 +00001285# Collect all command help into docstring
1286
1287# unfortunately we can't guess this order from the class definition
1288_help_order = [
1289 'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable',
1290 'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until',
Georg Brandle59ca2a2010-07-30 17:04:28 +00001291 'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist',
1292 'args', 'print', 'pp', 'whatis', 'source', 'alias', 'unalias',
1293 'debug', 'quit',
Georg Brandl0d089622010-07-30 16:00:46 +00001294]
1295
Georg Brandle59ca2a2010-07-30 17:04:28 +00001296docs = set()
Georg Brandl0d089622010-07-30 16:00:46 +00001297for _command in _help_order:
1298 __doc__ += getattr(Pdb, 'do_' + _command).__doc__.strip() + '\n\n'
1299__doc__ += Pdb.help_exec.__doc__
1300
1301del _help_order, _command
1302
Guido van Rossum35771131992-09-08 11:59:04 +00001303# Simplified interface
1304
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001305def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001306 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001307
1308def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001309 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001310
1311def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001312 # B/W compatibility
1313 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001314
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001315def runcall(*args, **kwds):
1316 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001317
Guido van Rossumb6775db1994-08-01 11:34:53 +00001318def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001319 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001320
1321# Post-Mortem interface
1322
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001323def post_mortem(t=None):
1324 # handling the default
1325 if t is None:
1326 # sys.exc_info() returns (type, value, traceback) if an exception is
1327 # being handled, otherwise it returns None
1328 t = sys.exc_info()[2]
Georg Brandl0d089622010-07-30 16:00:46 +00001329 if t is None:
1330 raise ValueError("A valid traceback must be passed if no "
1331 "exception is being handled")
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001332
Tim Peters2344fae2001-01-15 00:50:52 +00001333 p = Pdb()
1334 p.reset()
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001335 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001336
1337def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001338 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001339
1340
1341# Main program for testing
1342
Guido van Rossum23efba41992-01-27 16:58:47 +00001343TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001344
Guido van Rossum921c8241992-01-10 14:54:42 +00001345def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001346 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001347
1348# print help
1349def help():
Georg Brandl02053ee2010-07-18 10:11:03 +00001350 import pydoc
1351 pydoc.pager(__doc__)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001352
Georg Brandle0230912010-07-30 08:29:39 +00001353_usage = """\
1354usage: pdb.py [-c command] ... pyfile [arg] ...
1355
1356Debug the Python program given by pyfile.
1357
1358Initial commands are read from .pdbrc files in your home directory
1359and in the current directory, if they exist. Commands supplied with
1360-c are executed after commands from .pdbrc files.
1361
1362To let the script run until an exception occurs, use "-c continue".
Georg Brandl2dfec552010-07-30 08:43:32 +00001363To let the script run up to a given line X in the debugged file, use
1364"-c 'until X'"."""
Georg Brandle0230912010-07-30 08:29:39 +00001365
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001366def main():
Georg Brandle0230912010-07-30 08:29:39 +00001367 import getopt
1368
1369 opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['--help', '--command='])
1370
1371 if not args:
1372 print(_usage)
Tim Peters2344fae2001-01-15 00:50:52 +00001373 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001374
Georg Brandle0230912010-07-30 08:29:39 +00001375 commands = []
1376 for opt, optarg in opts:
1377 if opt in ['-h', '--help']:
1378 print(_usage)
1379 sys.exit()
1380 elif opt in ['-c', '--command']:
1381 commands.append(optarg)
1382
1383 mainpyfile = args[0] # Get script filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001384 if not os.path.exists(mainpyfile):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001385 print('Error:', mainpyfile, 'does not exist')
Tim Peters2344fae2001-01-15 00:50:52 +00001386 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001387
Georg Brandle0230912010-07-30 08:29:39 +00001388 sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001389
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001390 # Replace pdb's dir with script's dir in front of module search path.
1391 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001392
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001393 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1394 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl3078df02009-05-05 09:11:31 +00001395 # changed by the user from the command line. There is a "restart" command
1396 # which allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001397 pdb = Pdb()
Georg Brandle0230912010-07-30 08:29:39 +00001398 pdb.rcLines.extend(commands)
Georg Brandl1e30bd32010-07-30 07:21:26 +00001399 while True:
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001400 try:
1401 pdb._runscript(mainpyfile)
1402 if pdb._user_requested_quit:
1403 break
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001404 print("The program finished and will be restarted")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001405 except Restart:
1406 print("Restarting", mainpyfile, "with arguments:")
Georg Brandle0230912010-07-30 08:29:39 +00001407 print("\t" + " ".join(args))
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001408 except SystemExit:
1409 # In most cases SystemExit does not warrant a post-mortem session.
Georg Brandle0230912010-07-30 08:29:39 +00001410 print("The program exited via sys.exit(). Exit status:", end=' ')
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001411 print(sys.exc_info()[1])
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001412 except:
1413 traceback.print_exc()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001414 print("Uncaught exception. Entering post mortem debugging")
1415 print("Running 'cont' or 'step' will restart the program")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001416 t = sys.exc_info()[2]
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001417 pdb.interaction(None, t)
Georg Brandl3078df02009-05-05 09:11:31 +00001418 print("Post mortem debugger finished. The " + mainpyfile +
1419 " will be restarted")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001420
1421
1422# When invoked as main program, invoke the debugger on a script
Guido van Rossumd8faa362007-04-27 19:54:29 +00001423if __name__ == '__main__':
1424 import pdb
1425 pdb.main()