blob: 83e1197b7c9305c627b85b5cfba9b3f835f63857 [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
Georg Brandl0a9c3e92010-07-30 18:46:38 +000073import dis
Guido van Rossumb5699c71998-07-20 23:13:54 +000074import os
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000075import re
Georg Brandl0a9c3e92010-07-30 18:46:38 +000076import code
Barry Warsaw210bd202002-11-05 22:40:20 +000077import pprint
Johannes Gijsbers25b38c82004-10-12 18:12:09 +000078import traceback
Georg Brandle59ca2a2010-07-30 17:04:28 +000079import inspect
80import types
Guido van Rossumd8faa362007-04-27 19:54:29 +000081
82
83class Restart(Exception):
84 """Causes a debugger to be restarted for the debugged python program."""
85 pass
86
Skip Montanaro352674d2001-02-07 23:14:30 +000087__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
88 "post_mortem", "help"]
89
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000090def find_function(funcname, filename):
Thomas Wouters89f507f2006-12-13 04:49:30 +000091 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
Tim Peters2344fae2001-01-15 00:50:52 +000092 try:
93 fp = open(filename)
94 except IOError:
95 return None
96 # consumer of this info expects the first line to be 1
97 lineno = 1
98 answer = None
99 while 1:
100 line = fp.readline()
101 if line == '':
102 break
103 if cre.match(line):
104 answer = funcname, filename, lineno
105 break
106 lineno = lineno + 1
107 fp.close()
108 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +0000109
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000110def getsourcelines(obj):
111 lines, lineno = inspect.findsource(obj)
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000112 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000113 # must be a module frame: do not try to cut a block out of it
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000114 return lines, 1
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000115 elif inspect.ismodule(obj):
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000116 return lines, 1
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000117 return inspect.getblock(lines[lineno:]), lineno+1
Guido van Rossum921c8241992-01-10 14:54:42 +0000118
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000119def lasti2lineno(code, lasti):
120 linestarts = list(dis.findlinestarts(code))
121 linestarts.reverse()
122 for i, lineno in linestarts:
123 if lasti >= i:
124 return lineno
125 return 0
126
127
Guido van Rossuma558e371994-11-10 22:27:35 +0000128# Interaction prompt line will separate file and call info from code
129# text using value of line_prefix string. A newline and arrow may
130# be to your liking. You can set it once pdb is imported using the
131# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +0000132# line_prefix = ': ' # Use this to get the old situation back
133line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +0000134
Guido van Rossum23efba41992-01-27 16:58:47 +0000135class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +0000136
Georg Brandl243ad662009-05-05 09:00:19 +0000137 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None):
138 bdb.Bdb.__init__(self, skip=skip)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000139 cmd.Cmd.__init__(self, completekey, stdin, stdout)
140 if stdout:
141 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000142 self.prompt = '(Pdb) '
143 self.aliases = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000144 self.mainpyfile = ''
145 self._wait_for_mainpyfile = 0
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000146 self.tb_lineno = {}
Tim Peters2344fae2001-01-15 00:50:52 +0000147 # Try to load readline if it exists
148 try:
149 import readline
150 except ImportError:
151 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000152
Tim Peters2344fae2001-01-15 00:50:52 +0000153 # Read $HOME/.pdbrc and ./.pdbrc
154 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +0000155 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +0000156 envHome = os.environ['HOME']
157 try:
158 rcFile = open(os.path.join(envHome, ".pdbrc"))
159 except IOError:
160 pass
161 else:
162 for line in rcFile.readlines():
163 self.rcLines.append(line)
164 rcFile.close()
165 try:
166 rcFile = open(".pdbrc")
167 except IOError:
168 pass
169 else:
170 for line in rcFile.readlines():
171 self.rcLines.append(line)
172 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +0000173
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000174 self.commands = {} # associates a command list to breakpoint numbers
Benjamin Petersond23f8222009-04-05 19:13:16 +0000175 self.commands_doprompt = {} # for each bp num, tells if the prompt
176 # must be disp. after execing the cmd list
177 self.commands_silent = {} # for each bp num, tells if the stack trace
178 # must be disp. after execing the cmd list
179 self.commands_defining = False # True while in the process of defining
180 # a command list
181 self.commands_bnum = None # The breakpoint number for which we are
182 # defining a list
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000183
Tim Peters2344fae2001-01-15 00:50:52 +0000184 def reset(self):
185 bdb.Bdb.reset(self)
186 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000187
Tim Peters2344fae2001-01-15 00:50:52 +0000188 def forget(self):
189 self.lineno = None
190 self.stack = []
191 self.curindex = 0
192 self.curframe = None
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000193 self.tb_lineno.clear()
Guido van Rossum2424f851998-09-11 22:50:09 +0000194
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000195 def setup(self, f, tb):
Tim Peters2344fae2001-01-15 00:50:52 +0000196 self.forget()
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000197 self.stack, self.curindex = self.get_stack(f, tb)
198 while tb:
199 # when setting up post-mortem debugging with a traceback, save all
200 # the original line numbers to be displayed along the current line
201 # numbers (which can be different, e.g. due to finally clauses)
202 lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti)
203 self.tb_lineno[tb.tb_frame] = lineno
204 tb = tb.tb_next
Tim Peters2344fae2001-01-15 00:50:52 +0000205 self.curframe = self.stack[self.curindex][0]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000206 # The f_locals dictionary is updated from the actual frame
207 # locals whenever the .f_locals accessor is called, so we
208 # cache it here to ensure that modifications are not overwritten.
209 self.curframe_locals = self.curframe.f_locals
Georg Brandle0230912010-07-30 08:29:39 +0000210 return self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000211
Tim Peters2344fae2001-01-15 00:50:52 +0000212 # Can be executed earlier than 'setup' if desired
213 def execRcLines(self):
Georg Brandle0230912010-07-30 08:29:39 +0000214 if not self.rcLines:
215 return
216 # local copy because of recursion
217 rcLines = self.rcLines
218 rcLines.reverse()
219 # execute every line only once
220 self.rcLines = []
221 while rcLines:
222 line = rcLines.pop().strip()
223 if line and line[0] != '#':
224 if self.onecmd(line):
225 # if onecmd returns True, the command wants to exit
226 # from the interaction, save leftover rc lines
227 # to execute before next interaction
228 self.rcLines += reversed(rcLines)
229 return True
Guido van Rossum2424f851998-09-11 22:50:09 +0000230
Tim Peters280488b2002-08-23 18:19:30 +0000231 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000232
233 def user_call(self, frame, argument_list):
234 """This method is called when there is the remote possibility
235 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000236 if self._wait_for_mainpyfile:
237 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000238 if self.stop_here(frame):
Georg Brandl0d089622010-07-30 16:00:46 +0000239 self.message('--Call--')
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000240 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000241
Tim Peters2344fae2001-01-15 00:50:52 +0000242 def user_line(self, frame):
243 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000244 if self._wait_for_mainpyfile:
245 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
246 or frame.f_lineno<= 0):
247 return
248 self._wait_for_mainpyfile = 0
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000249 if self.bp_commands(frame):
250 self.interaction(frame, None)
251
Georg Brandle0230912010-07-30 08:29:39 +0000252 def bp_commands(self, frame):
Georg Brandl3078df02009-05-05 09:11:31 +0000253 """Call every command that was set for the current active breakpoint
254 (if there is one).
255
256 Returns True if the normal interaction function must be called,
257 False otherwise."""
258 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
259 if getattr(self, "currentbp", False) and \
260 self.currentbp in self.commands:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000261 currentbp = self.currentbp
262 self.currentbp = 0
263 lastcmd_back = self.lastcmd
264 self.setup(frame, None)
265 for line in self.commands[currentbp]:
266 self.onecmd(line)
267 self.lastcmd = lastcmd_back
268 if not self.commands_silent[currentbp]:
269 self.print_stack_entry(self.stack[self.curindex])
270 if self.commands_doprompt[currentbp]:
271 self.cmdloop()
272 self.forget()
273 return
274 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000275
Tim Peters2344fae2001-01-15 00:50:52 +0000276 def user_return(self, frame, return_value):
277 """This function is called when a return trap is set here."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000278 if self._wait_for_mainpyfile:
279 return
Tim Peters2344fae2001-01-15 00:50:52 +0000280 frame.f_locals['__return__'] = return_value
Georg Brandl0d089622010-07-30 16:00:46 +0000281 self.message('--Return--')
Tim Peters2344fae2001-01-15 00:50:52 +0000282 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000283
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000284 def user_exception(self, frame, exc_info):
Tim Peters2344fae2001-01-15 00:50:52 +0000285 """This function is called if an exception occurs,
286 but only if we are to stop at or just below this level."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000287 if self._wait_for_mainpyfile:
288 return
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000289 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000290 frame.f_locals['__exception__'] = exc_type, exc_value
Georg Brandl0d089622010-07-30 16:00:46 +0000291 self.message(traceback.format_exception_only(exc_type,
292 exc_value)[-1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000293 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000294
Tim Peters2344fae2001-01-15 00:50:52 +0000295 # General interaction function
296
297 def interaction(self, frame, traceback):
Georg Brandle0230912010-07-30 08:29:39 +0000298 if self.setup(frame, traceback):
299 # no interaction desired at this time (happens if .pdbrc contains
300 # a command like "continue")
301 self.forget()
302 return
Tim Peters2344fae2001-01-15 00:50:52 +0000303 self.print_stack_entry(self.stack[self.curindex])
304 self.cmdloop()
305 self.forget()
306
Benjamin Petersond23f8222009-04-05 19:13:16 +0000307 def displayhook(self, obj):
308 """Custom displayhook for the exec in default(), which prevents
309 assignment of the _ variable in the builtins.
310 """
Georg Brandl9fa2e022009-09-16 16:40:45 +0000311 # reproduce the behavior of the standard displayhook, not printing None
312 if obj is not None:
Georg Brandl0d089622010-07-30 16:00:46 +0000313 self.message(repr(obj))
Benjamin Petersond23f8222009-04-05 19:13:16 +0000314
Tim Peters2344fae2001-01-15 00:50:52 +0000315 def default(self, line):
316 if line[:1] == '!': line = line[1:]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000317 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000318 globals = self.curframe.f_globals
319 try:
320 code = compile(line + '\n', '<stdin>', 'single')
Christian Heimes679db4a2008-01-18 09:56:22 +0000321 save_stdout = sys.stdout
322 save_stdin = sys.stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000323 save_displayhook = sys.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000324 try:
325 sys.stdin = self.stdin
326 sys.stdout = self.stdout
Benjamin Petersond23f8222009-04-05 19:13:16 +0000327 sys.displayhook = self.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000328 exec(code, globals, locals)
329 finally:
330 sys.stdout = save_stdout
331 sys.stdin = save_stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000332 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000333 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000334 exc_info = sys.exc_info()[:2]
335 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000336
337 def precmd(self, line):
338 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000339 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000340 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000341 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000342 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000343 line = self.aliases[args[0]]
344 ii = 1
345 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000346 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000347 tmpArg)
348 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000349 line = line.replace("%*", ' '.join(args[1:]))
350 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000351 # split into ';;' separated commands
352 # unless it's an alias command
353 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000354 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000355 if marker >= 0:
356 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000357 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000358 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000359 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000360 return line
361
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000362 def onecmd(self, line):
363 """Interpret the argument as though it had been typed in response
364 to the prompt.
365
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000366 Checks whether this line is typed at the normal prompt or in
367 a breakpoint command list definition.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000368 """
369 if not self.commands_defining:
370 return cmd.Cmd.onecmd(self, line)
371 else:
372 return self.handle_command_def(line)
373
374 def handle_command_def(self,line):
Georg Brandl44f8bf92010-07-30 08:54:49 +0000375 """Handles one command line during command list definition."""
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000376 cmd, arg, line = self.parseline(line)
Georg Brandl44f8bf92010-07-30 08:54:49 +0000377 if not cmd:
378 return
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000379 if cmd == 'silent':
380 self.commands_silent[self.commands_bnum] = True
381 return # continue to handle other cmd def in the cmd list
382 elif cmd == 'end':
383 self.cmdqueue = []
384 return 1 # end of cmd list
385 cmdlist = self.commands[self.commands_bnum]
Georg Brandl44f8bf92010-07-30 08:54:49 +0000386 if arg:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000387 cmdlist.append(cmd+' '+arg)
388 else:
389 cmdlist.append(cmd)
390 # Determine if we must stop
391 try:
392 func = getattr(self, 'do_' + cmd)
393 except AttributeError:
394 func = self.default
Georg Brandl3078df02009-05-05 09:11:31 +0000395 # one of the resuming commands
396 if func.__name__ in self.commands_resuming:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000397 self.commands_doprompt[self.commands_bnum] = False
398 self.cmdqueue = []
399 return 1
400 return
401
Georg Brandl0d089622010-07-30 16:00:46 +0000402 # interface abstraction functions
403
404 def message(self, msg):
405 print(msg, file=self.stdout)
406
407 def error(self, msg):
408 print('***', msg, file=self.stdout)
409
Tim Peters2344fae2001-01-15 00:50:52 +0000410 # Command definitions, called by cmdloop()
411 # The argument is the remaining string on the command line
412 # Return true to exit from the command loop
413
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000414 def do_commands(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000415 """commands [bpnumber]
416 (com) ...
417 (com) end
418 (Pdb)
Georg Brandl3078df02009-05-05 09:11:31 +0000419
Georg Brandl0d089622010-07-30 16:00:46 +0000420 Specify a list of commands for breakpoint number bpnumber.
421 The commands themselves are entered on the following lines.
422 Type a line containing just 'end' to terminate the commands.
423 The commands are executed when the breakpoint is hit.
424
425 To remove all commands from a breakpoint, type commands and
426 follow it immediately with end; that is, give no commands.
427
428 With no bpnumber argument, commands refers to the last
429 breakpoint set.
430
431 You can use breakpoint commands to start your program up
432 again. Simply use the continue command, or step, or any other
433 command that resumes execution.
434
435 Specifying any command resuming execution (currently continue,
436 step, next, return, jump, quit and their abbreviations)
437 terminates the command list (as if that command was
438 immediately followed by end). This is because any time you
439 resume execution (even with a simple next or step), you may
440 encounter another breakpoint -- which could have its own
441 command list, leading to ambiguities about which list to
442 execute.
443
444 If you use the 'silent' command in the command list, the usual
445 message about stopping at a breakpoint is not printed. This
446 may be desirable for breakpoints that are to print a specific
447 message and then continue. If none of the other commands
448 print anything, you will see no sign that the breakpoint was
449 reached.
450 """
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000451 if not arg:
Georg Brandl7410dd12010-07-30 12:01:20 +0000452 bnum = len(bdb.Breakpoint.bpbynumber) - 1
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000453 else:
454 try:
455 bnum = int(arg)
456 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000457 self.error("Usage: commands [bnum]\n ...\n end")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000458 return
459 self.commands_bnum = bnum
460 self.commands[bnum] = []
461 self.commands_doprompt[bnum] = True
462 self.commands_silent[bnum] = False
463 prompt_back = self.prompt
464 self.prompt = '(com) '
465 self.commands_defining = True
Georg Brandl44f8bf92010-07-30 08:54:49 +0000466 try:
467 self.cmdloop()
468 finally:
469 self.commands_defining = False
470 self.prompt = prompt_back
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000471
Tim Peters2344fae2001-01-15 00:50:52 +0000472 def do_break(self, arg, temporary = 0):
Georg Brandl0d089622010-07-30 16:00:46 +0000473 """b(reak) [ ([filename:]lineno | function) [, condition] ]
474 Without argument, list all breaks.
475
476 With a line number argument, set a break at this line in the
477 current file. With a function name, set a break at the first
478 executable line of that function. If a second argument is
479 present, it is a string specifying an expression which must
480 evaluate to true before the breakpoint is honored.
481
482 The line number may be prefixed with a filename and a colon,
483 to specify a breakpoint in another file (probably one that
484 hasn't been loaded yet). The file is searched for on
485 sys.path; the .py suffix may be omitted.
486 """
Tim Peters2344fae2001-01-15 00:50:52 +0000487 if not arg:
488 if self.breaks: # There's at least one
Georg Brandl0d089622010-07-30 16:00:46 +0000489 self.message("Num Type Disp Enb Where")
Tim Peters2344fae2001-01-15 00:50:52 +0000490 for bp in bdb.Breakpoint.bpbynumber:
491 if bp:
Georg Brandl0d089622010-07-30 16:00:46 +0000492 self.message(bp.bpformat())
Tim Peters2344fae2001-01-15 00:50:52 +0000493 return
494 # parse arguments; comma has lowest precedence
495 # and cannot occur in filename
496 filename = None
497 lineno = None
498 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000499 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000500 if comma > 0:
501 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000502 cond = arg[comma+1:].lstrip()
503 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000504 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000505 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000506 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000507 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000508 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000509 f = self.lookupmodule(filename)
510 if not f:
Georg Brandl0d089622010-07-30 16:00:46 +0000511 self.error('%r not found from sys.path' % filename)
Tim Peters2344fae2001-01-15 00:50:52 +0000512 return
513 else:
514 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000515 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000516 try:
517 lineno = int(arg)
Guido van Rossumb940e112007-01-10 16:19:56 +0000518 except ValueError as msg:
Georg Brandl0d089622010-07-30 16:00:46 +0000519 self.error('Bad lineno: %s' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000520 return
521 else:
522 # no colon; can be lineno or function
523 try:
524 lineno = int(arg)
525 except ValueError:
526 try:
527 func = eval(arg,
528 self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +0000529 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000530 except:
531 func = arg
532 try:
Christian Heimesff737952007-11-27 10:40:20 +0000533 if hasattr(func, '__func__'):
534 func = func.__func__
Neal Norwitz221085d2007-02-25 20:55:47 +0000535 code = func.__code__
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000536 #use co_name to identify the bkpt (function names
537 #could be aliased, but co_name is invariant)
538 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000539 lineno = code.co_firstlineno
540 filename = code.co_filename
541 except:
542 # last thing to try
543 (ok, filename, ln) = self.lineinfo(arg)
544 if not ok:
Georg Brandl0d089622010-07-30 16:00:46 +0000545 self.error('The specified object %r is not a function '
546 'or was not found along sys.path.' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000547 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000548 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000549 lineno = int(ln)
550 if not filename:
551 filename = self.defaultFile()
552 # Check for reasonable breakpoint
553 line = self.checkline(filename, lineno)
554 if line:
555 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000556 err = self.set_break(filename, line, temporary, cond, funcname)
Georg Brandl0d089622010-07-30 16:00:46 +0000557 if err:
558 self.error(err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000559 else:
560 bp = self.get_breaks(filename, line)[-1]
Georg Brandl0d089622010-07-30 16:00:46 +0000561 self.message("Breakpoint %d at %s:%d" %
562 (bp.number, bp.file, bp.line))
Tim Peters2344fae2001-01-15 00:50:52 +0000563
564 # To be overridden in derived debuggers
565 def defaultFile(self):
566 """Produce a reasonable default."""
567 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000568 if filename == '<string>' and self.mainpyfile:
569 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000570 return filename
571
572 do_b = do_break
573
574 def do_tbreak(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000575 """tbreak [ ([filename:]lineno | function) [, condition] ]
576 Same arguments as break, but sets a temporary breakpoint: it
577 is automatically deleted when first hit.
578 """
Tim Peters2344fae2001-01-15 00:50:52 +0000579 self.do_break(arg, 1)
580
581 def lineinfo(self, identifier):
582 failed = (None, None, None)
583 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000584 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000585 if len(idstring) == 1:
586 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000587 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000588 elif len(idstring) == 3:
589 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000590 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000591 else:
592 return failed
593 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000594 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000595 # Protection for derived debuggers
596 if parts[0] == 'self':
597 del parts[0]
598 if len(parts) == 0:
599 return failed
600 # Best first guess at file to look at
601 fname = self.defaultFile()
602 if len(parts) == 1:
603 item = parts[0]
604 else:
605 # More than one part.
606 # First is module, second is method/class
607 f = self.lookupmodule(parts[0])
608 if f:
609 fname = f
610 item = parts[1]
611 answer = find_function(item, fname)
612 return answer or failed
613
614 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000615 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000616
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000617 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
618 line or EOF). Warning: testing is not comprehensive.
619 """
Georg Brandl1e30bd32010-07-30 07:21:26 +0000620 # this method should be callable before starting debugging, so default
621 # to "no globals" if there is no current frame
622 globs = self.curframe.f_globals if hasattr(self, 'curframe') else None
623 line = linecache.getline(filename, lineno, globs)
Tim Peters2344fae2001-01-15 00:50:52 +0000624 if not line:
Georg Brandl0d089622010-07-30 16:00:46 +0000625 self.message('End of file')
Tim Peters2344fae2001-01-15 00:50:52 +0000626 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000627 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000628 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000629 if (not line or (line[0] == '#') or
630 (line[:3] == '"""') or line[:3] == "'''"):
Georg Brandl0d089622010-07-30 16:00:46 +0000631 self.error('Blank or comment')
Tim Peters2344fae2001-01-15 00:50:52 +0000632 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000633 return lineno
634
635 def do_enable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000636 """enable bpnumber [bpnumber ...]
637 Enables the breakpoints given as a space separated list of
638 breakpoint numbers.
639 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000640 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000641 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000642 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000643 bp = self.get_bpbynumber(i)
644 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000645 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000646 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000647 bp.enable()
Georg Brandl0d089622010-07-30 16:00:46 +0000648 self.message('Enabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000649
650 def do_disable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000651 """disable bpnumber [bpnumber ...]
652 Disables the breakpoints given as a space separated list of
653 breakpoint numbers. Disabling a breakpoint means it cannot
654 cause the program to stop execution, but unlike clearing a
655 breakpoint, it remains in the list of breakpoints and can be
656 (re-)enabled.
657 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000658 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000659 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000660 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000661 bp = self.get_bpbynumber(i)
662 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000663 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000664 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000665 bp.disable()
Georg Brandl0d089622010-07-30 16:00:46 +0000666 self.message('Disabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000667
668 def do_condition(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000669 """condition bpnumber [condition]
670 Set a new condition for the breakpoint, an expression which
671 must evaluate to true before the breakpoint is honored. If
672 condition is absent, any existing condition is removed; i.e.,
673 the breakpoint is made unconditional.
674 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000675 args = arg.split(' ', 1)
Thomas Woutersb2137042007-02-01 18:02:27 +0000676 try:
Tim Peters2344fae2001-01-15 00:50:52 +0000677 cond = args[1]
Georg Brandl7410dd12010-07-30 12:01:20 +0000678 except IndexError:
Tim Peters2344fae2001-01-15 00:50:52 +0000679 cond = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000680 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000681 bp = self.get_bpbynumber(args[0].strip())
682 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000683 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000684 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000685 bp.cond = cond
686 if not cond:
Georg Brandl0d089622010-07-30 16:00:46 +0000687 self.message('Breakpoint %d is now unconditional.' % bp.number)
Georg Brandl7410dd12010-07-30 12:01:20 +0000688 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000689 self.message('New condition set for breakpoint %d.' % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000690
Georg Brandl7410dd12010-07-30 12:01:20 +0000691 def do_ignore(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000692 """ignore bpnumber [count]
693 Set the ignore count for the given breakpoint number. If
694 count is omitted, the ignore count is set to 0. A breakpoint
695 becomes active when the ignore count is zero. When non-zero,
696 the count is decremented each time the breakpoint is reached
697 and the breakpoint is not disabled and any associated
698 condition evaluates to true.
699 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000700 args = arg.split()
Thomas Woutersb2137042007-02-01 18:02:27 +0000701 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000702 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000703 except:
704 count = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +0000705 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000706 bp = self.get_bpbynumber(args[0].strip())
707 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000708 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000709 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000710 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000711 if count > 0:
Guido van Rossum08454592002-07-12 13:10:53 +0000712 if count > 1:
Georg Brandl0d089622010-07-30 16:00:46 +0000713 countstr = '%d crossings' % count
Tim Peters2344fae2001-01-15 00:50:52 +0000714 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000715 countstr = '1 crossing'
716 self.message('Will ignore next %s of breakpoint %d.' %
717 (countstr, bp.number))
Tim Peters2344fae2001-01-15 00:50:52 +0000718 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000719 self.message('Will stop next time breakpoint %d is reached.'
720 % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000721
722 def do_clear(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000723 """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]]
724 With a space separated list of breakpoint numbers, clear
725 those breakpoints. Without argument, clear all breaks (but
726 first ask confirmation). With a filename:lineno argument,
727 clear all breaks at that line in that file.
728 """
Tim Peters2344fae2001-01-15 00:50:52 +0000729 if not arg:
730 try:
Guido van Rossumc5b6ab02007-05-27 09:19:52 +0000731 reply = input('Clear all breaks? ')
Tim Peters2344fae2001-01-15 00:50:52 +0000732 except EOFError:
733 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000734 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000735 if reply in ('y', 'yes'):
Georg Brandl7410dd12010-07-30 12:01:20 +0000736 bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp]
Tim Peters2344fae2001-01-15 00:50:52 +0000737 self.clear_all_breaks()
Georg Brandl7410dd12010-07-30 12:01:20 +0000738 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000739 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000740 return
741 if ':' in arg:
742 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000743 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000744 filename = arg[:i]
745 arg = arg[i+1:]
746 try:
747 lineno = int(arg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000748 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000749 err = "Invalid line number (%s)" % arg
750 else:
Georg Brandl7410dd12010-07-30 12:01:20 +0000751 bplist = self.get_breaks(filename, lineno)
Tim Peters2344fae2001-01-15 00:50:52 +0000752 err = self.clear_break(filename, lineno)
Georg Brandl7410dd12010-07-30 12:01:20 +0000753 if err:
Georg Brandl0d089622010-07-30 16:00:46 +0000754 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000755 else:
756 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000757 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000758 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000759 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000760 for i in numberlist:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000761 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000762 bp = self.get_bpbynumber(i)
763 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000764 self.error(err)
Tim Peters2344fae2001-01-15 00:50:52 +0000765 else:
Georg Brandl7410dd12010-07-30 12:01:20 +0000766 self.clear_break(bp.file, bp.line)
Georg Brandl0d089622010-07-30 16:00:46 +0000767 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000768 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
769
770 def do_where(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000771 """w(here)
772 Print a stack trace, with the most recent frame at the bottom.
773 An arrow indicates the "current frame", which determines the
774 context of most commands. 'bt' is an alias for this command.
775 """
Tim Peters2344fae2001-01-15 00:50:52 +0000776 self.print_stack_trace()
777 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000778 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000779
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000780 def _select_frame(self, number):
781 assert 0 <= number < len(self.stack)
782 self.curindex = number
783 self.curframe = self.stack[self.curindex][0]
784 self.curframe_locals = self.curframe.f_locals
785 self.print_stack_entry(self.stack[self.curindex])
786 self.lineno = None
787
Tim Peters2344fae2001-01-15 00:50:52 +0000788 def do_up(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000789 """u(p) [count]
790 Move the current frame count (default one) levels up in the
791 stack trace (to an older frame).
792 """
Tim Peters2344fae2001-01-15 00:50:52 +0000793 if self.curindex == 0:
Georg Brandl0d089622010-07-30 16:00:46 +0000794 self.error('Oldest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000795 return
796 try:
797 count = int(arg or 1)
798 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000799 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000800 return
801 if count < 0:
802 newframe = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000803 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000804 newframe = max(0, self.curindex - count)
805 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000806 do_u = do_up
807
808 def do_down(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000809 """d(own) [count]
810 Move the current frame count (default one) levels down in the
811 stack trace (to a newer frame).
812 """
Tim Peters2344fae2001-01-15 00:50:52 +0000813 if self.curindex + 1 == len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +0000814 self.error('Newest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000815 return
816 try:
817 count = int(arg or 1)
818 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000819 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000820 return
821 if count < 0:
822 newframe = len(self.stack) - 1
Tim Peters2344fae2001-01-15 00:50:52 +0000823 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000824 newframe = min(len(self.stack) - 1, self.curindex + count)
825 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000826 do_d = do_down
827
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000828 def do_until(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000829 """unt(il) [lineno]
830 Without argument, continue execution until the line with a
831 number greater than the current one is reached. With a line
832 number, continue execution until a line with a number greater
833 or equal to that is reached. In both cases, also stop when
834 the current frame returns.
835 """
Georg Brandl2dfec552010-07-30 08:43:32 +0000836 if arg:
837 try:
838 lineno = int(arg)
839 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000840 self.error('Error in argument: %r' % arg)
Georg Brandl2dfec552010-07-30 08:43:32 +0000841 return
842 if lineno <= self.curframe.f_lineno:
Georg Brandl0d089622010-07-30 16:00:46 +0000843 self.error('"until" line number is smaller than current '
844 'line number')
Georg Brandl2dfec552010-07-30 08:43:32 +0000845 return
846 else:
847 lineno = None
848 self.set_until(self.curframe, lineno)
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000849 return 1
850 do_unt = do_until
851
Tim Peters2344fae2001-01-15 00:50:52 +0000852 def do_step(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000853 """s(tep)
854 Execute the current line, stop at the first possible occasion
855 (either in a function that is called or in the current
856 function).
857 """
Tim Peters2344fae2001-01-15 00:50:52 +0000858 self.set_step()
859 return 1
860 do_s = do_step
861
862 def do_next(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000863 """n(ext)
864 Continue execution until the next line in the current function
865 is reached or it returns.
866 """
Tim Peters2344fae2001-01-15 00:50:52 +0000867 self.set_next(self.curframe)
868 return 1
869 do_n = do_next
870
Guido van Rossumd8faa362007-04-27 19:54:29 +0000871 def do_run(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000872 """run [args...]
873 Restart the debugged python program. If a string is supplied
874 it is splitted with "shlex", and the result is used as the new
875 sys.argv. History, breakpoints, actions and debugger options
876 are preserved. "restart" is an alias for "run".
877 """
Guido van Rossumd8faa362007-04-27 19:54:29 +0000878 if arg:
879 import shlex
880 argv0 = sys.argv[0:1]
881 sys.argv = shlex.split(arg)
882 sys.argv[:0] = argv0
Georg Brandl0d089622010-07-30 16:00:46 +0000883 # this is caught in the main debugger loop
Guido van Rossumd8faa362007-04-27 19:54:29 +0000884 raise Restart
885
886 do_restart = do_run
887
Tim Peters2344fae2001-01-15 00:50:52 +0000888 def do_return(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000889 """r(eturn)
890 Continue execution until the current function returns.
891 """
Tim Peters2344fae2001-01-15 00:50:52 +0000892 self.set_return(self.curframe)
893 return 1
894 do_r = do_return
895
896 def do_continue(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000897 """c(ont(inue))
898 Continue execution, only stop when a breakpoint is encountered.
899 """
Tim Peters2344fae2001-01-15 00:50:52 +0000900 self.set_continue()
901 return 1
902 do_c = do_cont = do_continue
903
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000904 def do_jump(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000905 """j(ump) lineno
906 Set the next line that will be executed. Only available in
907 the bottom-most frame. This lets you jump back and execute
908 code again, or jump forward to skip code that you don't want
909 to run.
910
911 It should be noted that not all jumps are allowed -- for
912 instance it is not possible to jump into the middle of a
913 for loop or out of a finally clause.
914 """
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000915 if self.curindex + 1 != len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +0000916 self.error('You can only jump within the bottom frame')
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000917 return
918 try:
919 arg = int(arg)
920 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000921 self.error("The 'jump' command requires a line number")
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000922 else:
923 try:
924 # Do the jump, fix up our copy of the stack, and display the
925 # new position
926 self.curframe.f_lineno = arg
927 self.stack[self.curindex] = self.stack[self.curindex][0], arg
928 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumb940e112007-01-10 16:19:56 +0000929 except ValueError as e:
Georg Brandl0d089622010-07-30 16:00:46 +0000930 self.error('Jump failed: %s' % e)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000931 do_j = do_jump
932
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000933 def do_debug(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000934 """debug code
935 Enter a recursive debugger that steps through the code
936 argument (which is an arbitrary expression or statement to be
937 executed in the current environment).
938 """
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000939 sys.settrace(None)
940 globals = self.curframe.f_globals
Benjamin Petersond23f8222009-04-05 19:13:16 +0000941 locals = self.curframe_locals
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000942 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +0000943 p.prompt = "(%s) " % self.prompt.strip()
Georg Brandl0d089622010-07-30 16:00:46 +0000944 self.message("ENTERING RECURSIVE DEBUGGER")
Guido van Rossumed538d82003-04-09 19:36:34 +0000945 sys.call_tracing(p.run, (arg, globals, locals))
Georg Brandl0d089622010-07-30 16:00:46 +0000946 self.message("LEAVING RECURSIVE DEBUGGER")
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000947 sys.settrace(self.trace_dispatch)
948 self.lastcmd = p.lastcmd
949
Tim Peters2344fae2001-01-15 00:50:52 +0000950 def do_quit(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000951 """q(uit)\nexit
952 Quit from the debugger. The program being executed is aborted.
953 """
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000954 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000955 self.set_quit()
956 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000957
Tim Peters2344fae2001-01-15 00:50:52 +0000958 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000959 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000960
Guido van Rossumeef26072003-01-13 21:13:55 +0000961 def do_EOF(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000962 """EOF
963 Handles the receipt of EOF as a command.
964 """
965 self.message('')
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000966 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000967 self.set_quit()
968 return 1
969
Tim Peters2344fae2001-01-15 00:50:52 +0000970 def do_args(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000971 """a(rgs)
972 Print the argument list of the current function.
973 """
Benjamin Petersond23f8222009-04-05 19:13:16 +0000974 co = self.curframe.f_code
975 dict = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000976 n = co.co_argcount
977 if co.co_flags & 4: n = n+1
978 if co.co_flags & 8: n = n+1
979 for i in range(n):
980 name = co.co_varnames[i]
Georg Brandl0d089622010-07-30 16:00:46 +0000981 if name in dict:
982 self.message('%s = %r' % (name, dict[name]))
983 else:
984 self.message('%s = *** undefined ***' % (name,))
Tim Peters2344fae2001-01-15 00:50:52 +0000985 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000986
Tim Peters2344fae2001-01-15 00:50:52 +0000987 def do_retval(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000988 """retval
989 Print the return value for the last return of a function.
990 """
Benjamin Petersond23f8222009-04-05 19:13:16 +0000991 if '__return__' in self.curframe_locals:
Georg Brandl0d089622010-07-30 16:00:46 +0000992 self.message(repr(self.curframe_locals['__return__']))
Tim Peters2344fae2001-01-15 00:50:52 +0000993 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000994 self.error('Not yet returned!')
Tim Peters2344fae2001-01-15 00:50:52 +0000995 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000996
Barry Warsaw210bd202002-11-05 22:40:20 +0000997 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000998 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +0000999 return eval(arg, self.curframe.f_globals, self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +00001000 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001001 exc_info = sys.exc_info()[:2]
1002 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Barry Warsaw210bd202002-11-05 22:40:20 +00001003 raise
Guido van Rossum2424f851998-09-11 22:50:09 +00001004
Barry Warsaw210bd202002-11-05 22:40:20 +00001005 def do_p(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001006 """p(rint) expression
1007 Print the value of the expression.
1008 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001009 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001010 self.message(repr(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001011 except:
1012 pass
Georg Brandlc9879242007-09-04 07:07:56 +00001013 # make "print" an alias of "p" since print isn't a Python statement anymore
1014 do_print = do_p
Barry Warsaw210bd202002-11-05 22:40:20 +00001015
1016 def do_pp(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001017 """pp expression
1018 Pretty-print the value of the expression.
1019 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001020 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001021 self.message(pprint.pformat(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001022 except:
1023 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001024
Tim Peters2344fae2001-01-15 00:50:52 +00001025 def do_list(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001026 """l(ist) [first [,last] | .]
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001027
1028 List source code for the current file. Without arguments,
1029 list 11 lines around the current line or continue the previous
1030 listing. With . as argument, list 11 lines around the current
1031 line. With one argument, list 11 lines starting at that line.
1032 With two arguments, list the given range; if the second
1033 argument is less than the first, it is a count.
1034
1035 The current line in the current frame is indicated by "->".
1036 If an exception is being debugged, the line where the
1037 exception was originally raised or propagated is indicated by
1038 ">>", if it differs from the current line.
Georg Brandl0d089622010-07-30 16:00:46 +00001039 """
Tim Peters2344fae2001-01-15 00:50:52 +00001040 self.lastcmd = 'list'
1041 last = None
Georg Brandla91a94b2010-07-30 07:14:01 +00001042 if arg and arg != '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001043 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001044 if ',' in arg:
1045 first, last = arg.split(',')
1046 first = int(first.strip())
1047 last = int(last.strip())
Tim Peters2344fae2001-01-15 00:50:52 +00001048 if last < first:
Georg Brandl0d089622010-07-30 16:00:46 +00001049 # assume it's a count
Tim Peters2344fae2001-01-15 00:50:52 +00001050 last = first + last
1051 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001052 first = int(arg.strip())
1053 first = max(1, first - 5)
1054 except ValueError:
1055 self.error('Error in argument: %r' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001056 return
Georg Brandla91a94b2010-07-30 07:14:01 +00001057 elif self.lineno is None or arg == '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001058 first = max(1, self.curframe.f_lineno - 5)
1059 else:
1060 first = self.lineno + 1
1061 if last is None:
1062 last = first + 10
1063 filename = self.curframe.f_code.co_filename
1064 breaklist = self.get_file_breaks(filename)
1065 try:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001066 lines = linecache.getlines(filename, self.curframe.f_globals)
1067 self._print_lines(lines[first-1:last], first, breaklist,
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001068 self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001069 self.lineno = min(last, len(lines))
1070 if len(lines) < last:
1071 self.message('[EOF]')
Tim Peters2344fae2001-01-15 00:50:52 +00001072 except KeyboardInterrupt:
1073 pass
1074 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +00001075
Georg Brandle59ca2a2010-07-30 17:04:28 +00001076 def do_longlist(self, arg):
1077 """longlist | ll
1078 List the whole source code for the current function or frame.
1079 """
1080 filename = self.curframe.f_code.co_filename
1081 breaklist = self.get_file_breaks(filename)
1082 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001083 lines, lineno = getsourcelines(self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001084 except IOError as err:
1085 self.error(err)
1086 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001087 self._print_lines(lines, lineno, breaklist, self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001088 do_ll = do_longlist
1089
1090 def do_source(self, arg):
1091 """source expression
1092 Try to get source code for the given object and display it.
1093 """
1094 try:
1095 obj = self._getval(arg)
1096 except:
1097 return
1098 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001099 lines, lineno = getsourcelines(obj)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001100 except (IOError, TypeError) as err:
1101 self.error(err)
1102 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001103 self._print_lines(lines, lineno)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001104
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001105 def _print_lines(self, lines, start, breaks=(), frame=None):
Georg Brandle59ca2a2010-07-30 17:04:28 +00001106 """Print a range of lines."""
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001107 if frame:
1108 current_lineno = frame.f_lineno
1109 exc_lineno = self.tb_lineno.get(frame, -1)
1110 else:
1111 current_lineno = exc_lineno = -1
Georg Brandle59ca2a2010-07-30 17:04:28 +00001112 for lineno, line in enumerate(lines, start):
1113 s = str(lineno).rjust(3)
1114 if len(s) < 4:
1115 s += ' '
1116 if lineno in breaks:
1117 s += 'B'
1118 else:
1119 s += ' '
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001120 if lineno == current_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001121 s += '->'
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001122 elif lineno == exc_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001123 s += '>>'
1124 self.message(s + '\t' + line.rstrip())
1125
Tim Peters2344fae2001-01-15 00:50:52 +00001126 def do_whatis(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001127 """whatis arg
1128 Print the type of the argument.
1129 """
Tim Peters2344fae2001-01-15 00:50:52 +00001130 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001131 value = self._getval(arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001132 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001133 # _getval() already printed the error
Tim Peters2344fae2001-01-15 00:50:52 +00001134 return
1135 code = None
1136 # Is it a function?
Georg Brandl0d089622010-07-30 16:00:46 +00001137 try:
1138 code = value.__code__
1139 except Exception:
1140 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001141 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001142 self.message('Function %s' % code.co_name)
Tim Peters2344fae2001-01-15 00:50:52 +00001143 return
1144 # Is it an instance method?
Georg Brandl0d089622010-07-30 16:00:46 +00001145 try:
1146 code = value.__func__.__code__
1147 except Exception:
1148 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001149 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001150 self.message('Method %s' % code.co_name)
1151 return
1152 # Is it a class?
1153 if value.__class__ is type:
1154 self.message('Class %s.%s' % (value.__module__, value.__name__))
Tim Peters2344fae2001-01-15 00:50:52 +00001155 return
1156 # None of the above...
Georg Brandl0d089622010-07-30 16:00:46 +00001157 self.message(type(value))
Guido van Rossum8e2ec561993-07-29 09:37:38 +00001158
Tim Peters2344fae2001-01-15 00:50:52 +00001159 def do_alias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001160 """alias [name [command [parameter parameter ...] ]]
1161 Create an alias called 'name' that executes 'command'. The
1162 command must *not* be enclosed in quotes. Replaceable
1163 parameters can be indicated by %1, %2, and so on, while %* is
1164 replaced by all the parameters. If no command is given, the
1165 current alias for name is shown. If no name is given, all
1166 aliases are listed.
1167
1168 Aliases may be nested and can contain anything that can be
1169 legally typed at the pdb prompt. Note! You *can* override
1170 internal pdb commands with aliases! Those internal commands
1171 are then hidden until the alias is removed. Aliasing is
1172 recursively applied to the first word of the command line; all
1173 other words in the line are left alone.
1174
1175 As an example, here are two useful aliases (especially when
1176 placed in the .pdbrc file):
1177
1178 # Print instance variables (usage "pi classInst")
1179 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
1180 # Print instance variables in self
1181 alias ps pi self
1182 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001183 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001184 if len(args) == 0:
Benjamin Petersonbe74a372009-09-11 21:17:13 +00001185 keys = sorted(self.aliases.keys())
Tim Peters2344fae2001-01-15 00:50:52 +00001186 for alias in keys:
Georg Brandl0d089622010-07-30 16:00:46 +00001187 self.message("%s = %s" % (alias, self.aliases[alias]))
Tim Peters2344fae2001-01-15 00:50:52 +00001188 return
Guido van Rossum08454592002-07-12 13:10:53 +00001189 if args[0] in self.aliases and len(args) == 1:
Georg Brandl0d089622010-07-30 16:00:46 +00001190 self.message("%s = %s" % (args[0], self.aliases[args[0]]))
Tim Peters2344fae2001-01-15 00:50:52 +00001191 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001192 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +00001193
Tim Peters2344fae2001-01-15 00:50:52 +00001194 def do_unalias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001195 """unalias name
1196 Delete the specified alias.
1197 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001198 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001199 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +00001200 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +00001201 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +00001202
Georg Brandl0d089622010-07-30 16:00:46 +00001203 # List of all the commands making the program resume execution.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001204 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
1205 'do_quit', 'do_jump']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001206
Tim Peters2344fae2001-01-15 00:50:52 +00001207 # Print a traceback starting at the top stack frame.
1208 # The most recently entered frame is printed last;
1209 # this is different from dbx and gdb, but consistent with
1210 # the Python interpreter's stack trace.
1211 # It is also consistent with the up/down commands (which are
1212 # compatible with dbx and gdb: up moves towards 'main()'
1213 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +00001214
Tim Peters2344fae2001-01-15 00:50:52 +00001215 def print_stack_trace(self):
1216 try:
1217 for frame_lineno in self.stack:
1218 self.print_stack_entry(frame_lineno)
1219 except KeyboardInterrupt:
1220 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001221
Tim Peters2344fae2001-01-15 00:50:52 +00001222 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
1223 frame, lineno = frame_lineno
1224 if frame is self.curframe:
Georg Brandl0d089622010-07-30 16:00:46 +00001225 prefix = '> '
Tim Peters2344fae2001-01-15 00:50:52 +00001226 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001227 prefix = ' '
1228 self.message(prefix +
1229 self.format_stack_entry(frame_lineno, prompt_prefix))
Guido van Rossum2424f851998-09-11 22:50:09 +00001230
Georg Brandl0d089622010-07-30 16:00:46 +00001231 # Provide help
Guido van Rossum921c8241992-01-10 14:54:42 +00001232
Georg Brandl0d089622010-07-30 16:00:46 +00001233 def do_help(self, arg):
1234 """h(elp)
1235 Without argument, print the list of available commands.
1236 With a command name as argument, print help about that command.
1237 "help pdb" shows the full pdb documentation.
1238 "help exec" gives help on the ! command.
1239 """
1240 if not arg:
1241 return cmd.Cmd.do_help(self, arg)
1242 try:
1243 try:
1244 topic = getattr(self, 'help_' + arg)
1245 return topic()
1246 except AttributeError:
1247 command = getattr(self, 'do_' + arg)
1248 except AttributeError:
1249 self.error('No help for %r' % arg)
1250 else:
1251 self.message(command.__doc__.rstrip())
Guido van Rossum921c8241992-01-10 14:54:42 +00001252
Georg Brandl0d089622010-07-30 16:00:46 +00001253 do_h = do_help
Barry Warsaw210bd202002-11-05 22:40:20 +00001254
Tim Peters2344fae2001-01-15 00:50:52 +00001255 def help_exec(self):
Georg Brandl0d089622010-07-30 16:00:46 +00001256 """(!) statement
1257 Execute the (one-line) statement in the context of the current
1258 stack frame. The exclamation point can be omitted unless the
1259 first word of the statement resembles a debugger command. To
1260 assign to a global variable you must always prefix the command
1261 with a 'global' command, e.g.:
1262 (Pdb) global list_options; list_options = ['-l']
1263 (Pdb)
1264 """
1265 self.message(self.help_exec.__doc__.strip())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001266
Tim Peters2344fae2001-01-15 00:50:52 +00001267 def help_pdb(self):
1268 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001269
Georg Brandl0d089622010-07-30 16:00:46 +00001270 # other helper functions
1271
Tim Peters2344fae2001-01-15 00:50:52 +00001272 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001273 """Helper function for break/clear parsing -- may be overridden.
1274
1275 lookupmodule() translates (possibly incomplete) file or module name
1276 into an absolute file name.
1277 """
1278 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001279 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001280 f = os.path.join(sys.path[0], filename)
1281 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1282 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001283 root, ext = os.path.splitext(filename)
1284 if ext == '':
1285 filename = filename + '.py'
1286 if os.path.isabs(filename):
1287 return filename
1288 for dirname in sys.path:
1289 while os.path.islink(dirname):
1290 dirname = os.readlink(dirname)
1291 fullname = os.path.join(dirname, filename)
1292 if os.path.exists(fullname):
1293 return fullname
1294 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001295
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001296 def _runscript(self, filename):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001297 # The script has to run in __main__ namespace (or imports from
1298 # __main__ will break).
1299 #
1300 # So we clear up the __main__ and set several special variables
1301 # (this gets rid of pdb's globals and cleans old variables on restarts).
1302 import __main__
1303 __main__.__dict__.clear()
1304 __main__.__dict__.update({"__name__" : "__main__",
1305 "__file__" : filename,
1306 "__builtins__": __builtins__,
1307 })
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001308
1309 # When bdb sets tracing, a number of call and line events happens
1310 # BEFORE debugger even reaches user's code (and the exact sequence of
1311 # events depends on python version). So we take special measures to
1312 # avoid stopping before we reach the main script (see user_line and
1313 # user_call for details).
1314 self._wait_for_mainpyfile = 1
1315 self.mainpyfile = self.canonic(filename)
1316 self._user_requested_quit = 0
Georg Brandld07ac642009-08-13 07:50:57 +00001317 with open(filename, "rb") as fp:
1318 statement = "exec(compile(%r, %r, 'exec'))" % \
1319 (fp.read(), self.mainpyfile)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001320 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001321
Georg Brandl0d089622010-07-30 16:00:46 +00001322# Collect all command help into docstring
1323
1324# unfortunately we can't guess this order from the class definition
1325_help_order = [
1326 'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable',
1327 'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until',
Georg Brandle59ca2a2010-07-30 17:04:28 +00001328 'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist',
1329 'args', 'print', 'pp', 'whatis', 'source', 'alias', 'unalias',
1330 'debug', 'quit',
Georg Brandl0d089622010-07-30 16:00:46 +00001331]
1332
Georg Brandle59ca2a2010-07-30 17:04:28 +00001333docs = set()
Georg Brandl0d089622010-07-30 16:00:46 +00001334for _command in _help_order:
1335 __doc__ += getattr(Pdb, 'do_' + _command).__doc__.strip() + '\n\n'
1336__doc__ += Pdb.help_exec.__doc__
1337
1338del _help_order, _command
1339
Guido van Rossum35771131992-09-08 11:59:04 +00001340# Simplified interface
1341
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001342def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001343 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001344
1345def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001346 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001347
1348def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001349 # B/W compatibility
1350 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001351
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001352def runcall(*args, **kwds):
1353 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001354
Guido van Rossumb6775db1994-08-01 11:34:53 +00001355def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001356 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001357
1358# Post-Mortem interface
1359
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001360def post_mortem(t=None):
1361 # handling the default
1362 if t is None:
1363 # sys.exc_info() returns (type, value, traceback) if an exception is
1364 # being handled, otherwise it returns None
1365 t = sys.exc_info()[2]
Georg Brandl0d089622010-07-30 16:00:46 +00001366 if t is None:
1367 raise ValueError("A valid traceback must be passed if no "
1368 "exception is being handled")
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001369
Tim Peters2344fae2001-01-15 00:50:52 +00001370 p = Pdb()
1371 p.reset()
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001372 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001373
1374def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001375 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001376
1377
1378# Main program for testing
1379
Guido van Rossum23efba41992-01-27 16:58:47 +00001380TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001381
Guido van Rossum921c8241992-01-10 14:54:42 +00001382def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001383 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001384
1385# print help
1386def help():
Georg Brandl02053ee2010-07-18 10:11:03 +00001387 import pydoc
1388 pydoc.pager(__doc__)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001389
Georg Brandle0230912010-07-30 08:29:39 +00001390_usage = """\
1391usage: pdb.py [-c command] ... pyfile [arg] ...
1392
1393Debug the Python program given by pyfile.
1394
1395Initial commands are read from .pdbrc files in your home directory
1396and in the current directory, if they exist. Commands supplied with
1397-c are executed after commands from .pdbrc files.
1398
1399To let the script run until an exception occurs, use "-c continue".
Georg Brandl2dfec552010-07-30 08:43:32 +00001400To let the script run up to a given line X in the debugged file, use
1401"-c 'until X'"."""
Georg Brandle0230912010-07-30 08:29:39 +00001402
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001403def main():
Georg Brandle0230912010-07-30 08:29:39 +00001404 import getopt
1405
1406 opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['--help', '--command='])
1407
1408 if not args:
1409 print(_usage)
Tim Peters2344fae2001-01-15 00:50:52 +00001410 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001411
Georg Brandle0230912010-07-30 08:29:39 +00001412 commands = []
1413 for opt, optarg in opts:
1414 if opt in ['-h', '--help']:
1415 print(_usage)
1416 sys.exit()
1417 elif opt in ['-c', '--command']:
1418 commands.append(optarg)
1419
1420 mainpyfile = args[0] # Get script filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001421 if not os.path.exists(mainpyfile):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001422 print('Error:', mainpyfile, 'does not exist')
Tim Peters2344fae2001-01-15 00:50:52 +00001423 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001424
Georg Brandle0230912010-07-30 08:29:39 +00001425 sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001426
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001427 # Replace pdb's dir with script's dir in front of module search path.
1428 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001429
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001430 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1431 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl3078df02009-05-05 09:11:31 +00001432 # changed by the user from the command line. There is a "restart" command
1433 # which allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001434 pdb = Pdb()
Georg Brandle0230912010-07-30 08:29:39 +00001435 pdb.rcLines.extend(commands)
Georg Brandl1e30bd32010-07-30 07:21:26 +00001436 while True:
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001437 try:
1438 pdb._runscript(mainpyfile)
1439 if pdb._user_requested_quit:
1440 break
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001441 print("The program finished and will be restarted")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001442 except Restart:
1443 print("Restarting", mainpyfile, "with arguments:")
Georg Brandle0230912010-07-30 08:29:39 +00001444 print("\t" + " ".join(args))
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001445 except SystemExit:
1446 # In most cases SystemExit does not warrant a post-mortem session.
Georg Brandle0230912010-07-30 08:29:39 +00001447 print("The program exited via sys.exit(). Exit status:", end=' ')
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001448 print(sys.exc_info()[1])
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001449 except:
1450 traceback.print_exc()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001451 print("Uncaught exception. Entering post mortem debugging")
1452 print("Running 'cont' or 'step' will restart the program")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001453 t = sys.exc_info()[2]
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001454 pdb.interaction(None, t)
Georg Brandl3078df02009-05-05 09:11:31 +00001455 print("Post mortem debugger finished. The " + mainpyfile +
1456 " will be restarted")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001457
1458
1459# When invoked as main program, invoke the debugger on a script
Guido van Rossumd8faa362007-04-27 19:54:29 +00001460if __name__ == '__main__':
1461 import pdb
1462 pdb.main()