blob: 47972655f969fc5aa9aea496e73d99c671cc02e2 [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
Martin Pantere26da7c2016-06-02 10:07:09 +000055defined there can be overridden by the local file.
Georg Brandl02053ee2010-07-18 10:11:03 +000056
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
Georg Brandl44f2b642010-12-04 16:00:47 +000069import os
70import re
Guido van Rossum921c8241992-01-10 14:54:42 +000071import sys
Guido van Rossum23efba41992-01-27 16:58:47 +000072import cmd
73import bdb
Georg Brandl0a9c3e92010-07-30 18:46:38 +000074import dis
Georg Brandl1acb7462010-12-04 11:20:26 +000075import code
Georg Brandl4c7c3c52012-03-10 22:36:48 +010076import glob
Barry Warsaw210bd202002-11-05 22:40:20 +000077import pprint
Georg Brandl44f2b642010-12-04 16:00:47 +000078import signal
Georg Brandle59ca2a2010-07-30 17:04:28 +000079import inspect
Georg Brandl1acb7462010-12-04 11:20:26 +000080import traceback
81import linecache
Guido van Rossumd8faa362007-04-27 19:54:29 +000082
83
84class Restart(Exception):
85 """Causes a debugger to be restarted for the debugged python program."""
86 pass
87
Skip Montanaro352674d2001-02-07 23:14:30 +000088__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
89 "post_mortem", "help"]
90
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000091def find_function(funcname, filename):
Thomas Wouters89f507f2006-12-13 04:49:30 +000092 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
Tim Peters2344fae2001-01-15 00:50:52 +000093 try:
94 fp = open(filename)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +020095 except OSError:
Tim Peters2344fae2001-01-15 00:50:52 +000096 return None
97 # consumer of this info expects the first line to be 1
Georg Brandl6e220552013-10-13 20:51:47 +020098 with fp:
99 for lineno, line in enumerate(fp, start=1):
100 if cre.match(line):
101 return funcname, filename, lineno
102 return None
Guido van Rossum921c8241992-01-10 14:54:42 +0000103
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000104def getsourcelines(obj):
105 lines, lineno = inspect.findsource(obj)
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000106 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000107 # must be a module frame: do not try to cut a block out of it
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000108 return lines, 1
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000109 elif inspect.ismodule(obj):
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000110 return lines, 1
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000111 return inspect.getblock(lines[lineno:]), lineno+1
Guido van Rossum921c8241992-01-10 14:54:42 +0000112
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000113def lasti2lineno(code, lasti):
114 linestarts = list(dis.findlinestarts(code))
115 linestarts.reverse()
116 for i, lineno in linestarts:
117 if lasti >= i:
118 return lineno
119 return 0
120
121
Georg Brandlcbc79c72010-12-04 16:21:42 +0000122class _rstr(str):
123 """String that doesn't quote its repr."""
124 def __repr__(self):
125 return self
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
Xavier de Gaye10e54ae2016-10-12 20:13:24 +0200137 _previous_sigint_handler = None
138
Georg Brandl44f2b642010-12-04 16:00:47 +0000139 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None,
140 nosigint=False):
Georg Brandl243ad662009-05-05 09:00:19 +0000141 bdb.Bdb.__init__(self, skip=skip)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000142 cmd.Cmd.__init__(self, completekey, stdin, stdout)
143 if stdout:
144 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000145 self.prompt = '(Pdb) '
146 self.aliases = {}
Georg Brandlcbc79c72010-12-04 16:21:42 +0000147 self.displaying = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000148 self.mainpyfile = ''
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000149 self._wait_for_mainpyfile = False
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000150 self.tb_lineno = {}
Tim Peters2344fae2001-01-15 00:50:52 +0000151 # Try to load readline if it exists
152 try:
153 import readline
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100154 # remove some common file name delimiters
155 readline.set_completer_delims(' \t\n`@#$%^&*()=+[{]}\\|;:\'",<>?')
Brett Cannoncd171c82013-07-04 17:43:24 -0400156 except ImportError:
Tim Peters2344fae2001-01-15 00:50:52 +0000157 pass
Georg Brandl44f2b642010-12-04 16:00:47 +0000158 self.allow_kbdint = False
159 self.nosigint = nosigint
Guido van Rossum2424f851998-09-11 22:50:09 +0000160
Tim Peters2344fae2001-01-15 00:50:52 +0000161 # Read $HOME/.pdbrc and ./.pdbrc
162 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +0000163 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +0000164 envHome = os.environ['HOME']
165 try:
Florent Xicluna7dde7922010-09-03 19:52:03 +0000166 with open(os.path.join(envHome, ".pdbrc")) as rcFile:
167 self.rcLines.extend(rcFile)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200168 except OSError:
Tim Peters2344fae2001-01-15 00:50:52 +0000169 pass
Tim Peters2344fae2001-01-15 00:50:52 +0000170 try:
Florent Xicluna7dde7922010-09-03 19:52:03 +0000171 with open(".pdbrc") as rcFile:
172 self.rcLines.extend(rcFile)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200173 except OSError:
Tim Peters2344fae2001-01-15 00:50:52 +0000174 pass
Guido van Rossum23efba41992-01-27 16:58:47 +0000175
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000176 self.commands = {} # associates a command list to breakpoint numbers
Benjamin Petersond23f8222009-04-05 19:13:16 +0000177 self.commands_doprompt = {} # for each bp num, tells if the prompt
178 # must be disp. after execing the cmd list
179 self.commands_silent = {} # for each bp num, tells if the stack trace
180 # must be disp. after execing the cmd list
181 self.commands_defining = False # True while in the process of defining
182 # a command list
183 self.commands_bnum = None # The breakpoint number for which we are
184 # defining a list
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000185
Georg Brandl44f2b642010-12-04 16:00:47 +0000186 def sigint_handler(self, signum, frame):
187 if self.allow_kbdint:
188 raise KeyboardInterrupt
189 self.message("\nProgram interrupted. (Use 'cont' to resume).")
190 self.set_step()
191 self.set_trace(frame)
Georg Brandl44f2b642010-12-04 16:00:47 +0000192
Tim Peters2344fae2001-01-15 00:50:52 +0000193 def reset(self):
194 bdb.Bdb.reset(self)
195 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000196
Tim Peters2344fae2001-01-15 00:50:52 +0000197 def forget(self):
198 self.lineno = None
199 self.stack = []
200 self.curindex = 0
201 self.curframe = None
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000202 self.tb_lineno.clear()
Guido van Rossum2424f851998-09-11 22:50:09 +0000203
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000204 def setup(self, f, tb):
Tim Peters2344fae2001-01-15 00:50:52 +0000205 self.forget()
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000206 self.stack, self.curindex = self.get_stack(f, tb)
207 while tb:
208 # when setting up post-mortem debugging with a traceback, save all
209 # the original line numbers to be displayed along the current line
210 # numbers (which can be different, e.g. due to finally clauses)
211 lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti)
212 self.tb_lineno[tb.tb_frame] = lineno
213 tb = tb.tb_next
Tim Peters2344fae2001-01-15 00:50:52 +0000214 self.curframe = self.stack[self.curindex][0]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000215 # The f_locals dictionary is updated from the actual frame
216 # locals whenever the .f_locals accessor is called, so we
217 # cache it here to ensure that modifications are not overwritten.
218 self.curframe_locals = self.curframe.f_locals
Georg Brandle0230912010-07-30 08:29:39 +0000219 return self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000220
Tim Peters2344fae2001-01-15 00:50:52 +0000221 # Can be executed earlier than 'setup' if desired
222 def execRcLines(self):
Georg Brandle0230912010-07-30 08:29:39 +0000223 if not self.rcLines:
224 return
225 # local copy because of recursion
226 rcLines = self.rcLines
227 rcLines.reverse()
228 # execute every line only once
229 self.rcLines = []
230 while rcLines:
231 line = rcLines.pop().strip()
232 if line and line[0] != '#':
233 if self.onecmd(line):
234 # if onecmd returns True, the command wants to exit
235 # from the interaction, save leftover rc lines
236 # to execute before next interaction
237 self.rcLines += reversed(rcLines)
238 return True
Guido van Rossum2424f851998-09-11 22:50:09 +0000239
Tim Peters280488b2002-08-23 18:19:30 +0000240 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000241
242 def user_call(self, frame, argument_list):
243 """This method is called when there is the remote possibility
244 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000245 if self._wait_for_mainpyfile:
246 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000247 if self.stop_here(frame):
Georg Brandl0d089622010-07-30 16:00:46 +0000248 self.message('--Call--')
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000249 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000250
Tim Peters2344fae2001-01-15 00:50:52 +0000251 def user_line(self, frame):
252 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000253 if self._wait_for_mainpyfile:
254 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000255 or frame.f_lineno <= 0):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000256 return
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000257 self._wait_for_mainpyfile = False
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000258 if self.bp_commands(frame):
259 self.interaction(frame, None)
260
Georg Brandle0230912010-07-30 08:29:39 +0000261 def bp_commands(self, frame):
Georg Brandl3078df02009-05-05 09:11:31 +0000262 """Call every command that was set for the current active breakpoint
263 (if there is one).
264
265 Returns True if the normal interaction function must be called,
266 False otherwise."""
267 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
268 if getattr(self, "currentbp", False) and \
269 self.currentbp in self.commands:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000270 currentbp = self.currentbp
271 self.currentbp = 0
272 lastcmd_back = self.lastcmd
273 self.setup(frame, None)
274 for line in self.commands[currentbp]:
275 self.onecmd(line)
276 self.lastcmd = lastcmd_back
277 if not self.commands_silent[currentbp]:
278 self.print_stack_entry(self.stack[self.curindex])
279 if self.commands_doprompt[currentbp]:
Georg Brandl44f2b642010-12-04 16:00:47 +0000280 self._cmdloop()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000281 self.forget()
282 return
283 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000284
Tim Peters2344fae2001-01-15 00:50:52 +0000285 def user_return(self, frame, return_value):
286 """This function is called when a return trap is set here."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000287 if self._wait_for_mainpyfile:
288 return
Tim Peters2344fae2001-01-15 00:50:52 +0000289 frame.f_locals['__return__'] = return_value
Georg Brandl0d089622010-07-30 16:00:46 +0000290 self.message('--Return--')
Tim Peters2344fae2001-01-15 00:50:52 +0000291 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000292
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000293 def user_exception(self, frame, exc_info):
Tim Peters2344fae2001-01-15 00:50:52 +0000294 """This function is called if an exception occurs,
295 but only if we are to stop at or just below this level."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000296 if self._wait_for_mainpyfile:
297 return
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000298 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000299 frame.f_locals['__exception__'] = exc_type, exc_value
Guido van Rossum8820c232013-11-21 11:30:06 -0800300
301 # An 'Internal StopIteration' exception is an exception debug event
302 # issued by the interpreter when handling a subgenerator run with
Martin Panter46f50722016-05-26 05:35:26 +0000303 # 'yield from' or a generator controlled by a for loop. No exception has
Berker Peksagf23530f2014-10-19 18:04:38 +0300304 # actually occurred in this case. The debugger uses this debug event to
Guido van Rossum8820c232013-11-21 11:30:06 -0800305 # stop when the debuggee is returning from such generators.
306 prefix = 'Internal ' if (not exc_traceback
307 and exc_type is StopIteration) else ''
308 self.message('%s%s' % (prefix,
309 traceback.format_exception_only(exc_type, exc_value)[-1].strip()))
Tim Peters2344fae2001-01-15 00:50:52 +0000310 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000311
Tim Peters2344fae2001-01-15 00:50:52 +0000312 # General interaction function
Georg Brandl44f2b642010-12-04 16:00:47 +0000313 def _cmdloop(self):
314 while True:
315 try:
316 # keyboard interrupts allow for an easy way to cancel
317 # the current command, so allow them during interactive input
318 self.allow_kbdint = True
319 self.cmdloop()
320 self.allow_kbdint = False
321 break
322 except KeyboardInterrupt:
323 self.message('--KeyboardInterrupt--')
Tim Peters2344fae2001-01-15 00:50:52 +0000324
Georg Brandlcbc79c72010-12-04 16:21:42 +0000325 # Called before loop, handles display expressions
326 def preloop(self):
327 displaying = self.displaying.get(self.curframe)
328 if displaying:
329 for expr, oldvalue in displaying.items():
330 newvalue = self._getval_except(expr)
331 # check for identity first; this prevents custom __eq__ to
332 # be called at every loop, and also prevents instances whose
333 # fields are changed to be displayed
334 if newvalue is not oldvalue and newvalue != oldvalue:
335 displaying[expr] = newvalue
336 self.message('display %s: %r [old: %r]' %
337 (expr, newvalue, oldvalue))
338
Tim Peters2344fae2001-01-15 00:50:52 +0000339 def interaction(self, frame, traceback):
Xavier de Gaye10e54ae2016-10-12 20:13:24 +0200340 # Restore the previous signal handler at the Pdb prompt.
341 if Pdb._previous_sigint_handler:
342 signal.signal(signal.SIGINT, Pdb._previous_sigint_handler)
343 Pdb._previous_sigint_handler = None
Georg Brandle0230912010-07-30 08:29:39 +0000344 if self.setup(frame, traceback):
345 # no interaction desired at this time (happens if .pdbrc contains
346 # a command like "continue")
347 self.forget()
348 return
Tim Peters2344fae2001-01-15 00:50:52 +0000349 self.print_stack_entry(self.stack[self.curindex])
Georg Brandl44f2b642010-12-04 16:00:47 +0000350 self._cmdloop()
Tim Peters2344fae2001-01-15 00:50:52 +0000351 self.forget()
352
Benjamin Petersond23f8222009-04-05 19:13:16 +0000353 def displayhook(self, obj):
354 """Custom displayhook for the exec in default(), which prevents
355 assignment of the _ variable in the builtins.
356 """
Georg Brandl9fa2e022009-09-16 16:40:45 +0000357 # reproduce the behavior of the standard displayhook, not printing None
358 if obj is not None:
Georg Brandl0d089622010-07-30 16:00:46 +0000359 self.message(repr(obj))
Benjamin Petersond23f8222009-04-05 19:13:16 +0000360
Tim Peters2344fae2001-01-15 00:50:52 +0000361 def default(self, line):
362 if line[:1] == '!': line = line[1:]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000363 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000364 globals = self.curframe.f_globals
365 try:
366 code = compile(line + '\n', '<stdin>', 'single')
Christian Heimes679db4a2008-01-18 09:56:22 +0000367 save_stdout = sys.stdout
368 save_stdin = sys.stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000369 save_displayhook = sys.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000370 try:
371 sys.stdin = self.stdin
372 sys.stdout = self.stdout
Benjamin Petersond23f8222009-04-05 19:13:16 +0000373 sys.displayhook = self.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000374 exec(code, globals, locals)
375 finally:
376 sys.stdout = save_stdout
377 sys.stdin = save_stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000378 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000379 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000380 exc_info = sys.exc_info()[:2]
381 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000382
383 def precmd(self, line):
384 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000385 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000386 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000387 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000388 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000389 line = self.aliases[args[0]]
390 ii = 1
391 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000392 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000393 tmpArg)
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000394 ii += 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000395 line = line.replace("%*", ' '.join(args[1:]))
396 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000397 # split into ';;' separated commands
398 # unless it's an alias command
399 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000400 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000401 if marker >= 0:
402 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000403 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000404 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000405 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000406 return line
407
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000408 def onecmd(self, line):
409 """Interpret the argument as though it had been typed in response
410 to the prompt.
411
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000412 Checks whether this line is typed at the normal prompt or in
413 a breakpoint command list definition.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000414 """
415 if not self.commands_defining:
416 return cmd.Cmd.onecmd(self, line)
417 else:
418 return self.handle_command_def(line)
419
Georg Brandlb90ffd82010-07-30 22:20:16 +0000420 def handle_command_def(self, line):
Georg Brandl44f8bf92010-07-30 08:54:49 +0000421 """Handles one command line during command list definition."""
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000422 cmd, arg, line = self.parseline(line)
Georg Brandl44f8bf92010-07-30 08:54:49 +0000423 if not cmd:
424 return
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000425 if cmd == 'silent':
426 self.commands_silent[self.commands_bnum] = True
427 return # continue to handle other cmd def in the cmd list
428 elif cmd == 'end':
429 self.cmdqueue = []
430 return 1 # end of cmd list
431 cmdlist = self.commands[self.commands_bnum]
Georg Brandl44f8bf92010-07-30 08:54:49 +0000432 if arg:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000433 cmdlist.append(cmd+' '+arg)
434 else:
435 cmdlist.append(cmd)
436 # Determine if we must stop
437 try:
438 func = getattr(self, 'do_' + cmd)
439 except AttributeError:
440 func = self.default
Georg Brandl3078df02009-05-05 09:11:31 +0000441 # one of the resuming commands
442 if func.__name__ in self.commands_resuming:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000443 self.commands_doprompt[self.commands_bnum] = False
444 self.cmdqueue = []
445 return 1
446 return
447
Georg Brandl0d089622010-07-30 16:00:46 +0000448 # interface abstraction functions
449
450 def message(self, msg):
451 print(msg, file=self.stdout)
452
453 def error(self, msg):
454 print('***', msg, file=self.stdout)
455
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100456 # Generic completion functions. Individual complete_foo methods can be
457 # assigned below to one of these functions.
458
459 def _complete_location(self, text, line, begidx, endidx):
460 # Complete a file/module/function location for break/tbreak/clear.
461 if line.strip().endswith((':', ',')):
462 # Here comes a line number or a condition which we can't complete.
463 return []
464 # First, try to find matching functions (i.e. expressions).
465 try:
466 ret = self._complete_expression(text, line, begidx, endidx)
467 except Exception:
468 ret = []
469 # Then, try to complete file names as well.
470 globs = glob.glob(text + '*')
471 for fn in globs:
472 if os.path.isdir(fn):
473 ret.append(fn + '/')
474 elif os.path.isfile(fn) and fn.lower().endswith(('.py', '.pyw')):
475 ret.append(fn + ':')
476 return ret
477
478 def _complete_bpnumber(self, text, line, begidx, endidx):
479 # Complete a breakpoint number. (This would be more helpful if we could
480 # display additional info along with the completions, such as file/line
481 # of the breakpoint.)
482 return [str(i) for i, bp in enumerate(bdb.Breakpoint.bpbynumber)
483 if bp is not None and str(i).startswith(text)]
484
485 def _complete_expression(self, text, line, begidx, endidx):
486 # Complete an arbitrary expression.
487 if not self.curframe:
488 return []
489 # Collect globals and locals. It is usually not really sensible to also
490 # complete builtins, and they clutter the namespace quite heavily, so we
491 # leave them out.
492 ns = self.curframe.f_globals.copy()
493 ns.update(self.curframe_locals)
494 if '.' in text:
495 # Walk an attribute chain up to the last part, similar to what
496 # rlcompleter does. This will bail if any of the parts are not
497 # simple attribute access, which is what we want.
498 dotted = text.split('.')
499 try:
500 obj = ns[dotted[0]]
501 for part in dotted[1:-1]:
502 obj = getattr(obj, part)
503 except (KeyError, AttributeError):
504 return []
505 prefix = '.'.join(dotted[:-1]) + '.'
506 return [prefix + n for n in dir(obj) if n.startswith(dotted[-1])]
507 else:
508 # Complete a simple name.
509 return [n for n in ns.keys() if n.startswith(text)]
510
Tim Peters2344fae2001-01-15 00:50:52 +0000511 # Command definitions, called by cmdloop()
512 # The argument is the remaining string on the command line
513 # Return true to exit from the command loop
514
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000515 def do_commands(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000516 """commands [bpnumber]
517 (com) ...
518 (com) end
519 (Pdb)
Georg Brandl3078df02009-05-05 09:11:31 +0000520
Georg Brandl0d089622010-07-30 16:00:46 +0000521 Specify a list of commands for breakpoint number bpnumber.
522 The commands themselves are entered on the following lines.
523 Type a line containing just 'end' to terminate the commands.
524 The commands are executed when the breakpoint is hit.
525
526 To remove all commands from a breakpoint, type commands and
527 follow it immediately with end; that is, give no commands.
528
529 With no bpnumber argument, commands refers to the last
530 breakpoint set.
531
532 You can use breakpoint commands to start your program up
533 again. Simply use the continue command, or step, or any other
534 command that resumes execution.
535
536 Specifying any command resuming execution (currently continue,
537 step, next, return, jump, quit and their abbreviations)
538 terminates the command list (as if that command was
539 immediately followed by end). This is because any time you
540 resume execution (even with a simple next or step), you may
541 encounter another breakpoint -- which could have its own
542 command list, leading to ambiguities about which list to
543 execute.
544
545 If you use the 'silent' command in the command list, the usual
546 message about stopping at a breakpoint is not printed. This
547 may be desirable for breakpoints that are to print a specific
548 message and then continue. If none of the other commands
549 print anything, you will see no sign that the breakpoint was
550 reached.
551 """
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000552 if not arg:
Georg Brandl7410dd12010-07-30 12:01:20 +0000553 bnum = len(bdb.Breakpoint.bpbynumber) - 1
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000554 else:
555 try:
556 bnum = int(arg)
557 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000558 self.error("Usage: commands [bnum]\n ...\n end")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000559 return
560 self.commands_bnum = bnum
Georg Brandlb90ffd82010-07-30 22:20:16 +0000561 # Save old definitions for the case of a keyboard interrupt.
562 if bnum in self.commands:
563 old_command_defs = (self.commands[bnum],
564 self.commands_doprompt[bnum],
565 self.commands_silent[bnum])
566 else:
567 old_command_defs = None
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000568 self.commands[bnum] = []
569 self.commands_doprompt[bnum] = True
570 self.commands_silent[bnum] = False
Georg Brandlb90ffd82010-07-30 22:20:16 +0000571
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000572 prompt_back = self.prompt
573 self.prompt = '(com) '
574 self.commands_defining = True
Georg Brandl44f8bf92010-07-30 08:54:49 +0000575 try:
576 self.cmdloop()
Georg Brandlb90ffd82010-07-30 22:20:16 +0000577 except KeyboardInterrupt:
578 # Restore old definitions.
579 if old_command_defs:
580 self.commands[bnum] = old_command_defs[0]
581 self.commands_doprompt[bnum] = old_command_defs[1]
582 self.commands_silent[bnum] = old_command_defs[2]
583 else:
584 del self.commands[bnum]
585 del self.commands_doprompt[bnum]
586 del self.commands_silent[bnum]
587 self.error('command definition aborted, old commands restored')
Georg Brandl44f8bf92010-07-30 08:54:49 +0000588 finally:
589 self.commands_defining = False
590 self.prompt = prompt_back
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000591
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100592 complete_commands = _complete_bpnumber
593
Tim Peters2344fae2001-01-15 00:50:52 +0000594 def do_break(self, arg, temporary = 0):
Georg Brandl0d089622010-07-30 16:00:46 +0000595 """b(reak) [ ([filename:]lineno | function) [, condition] ]
596 Without argument, list all breaks.
597
598 With a line number argument, set a break at this line in the
599 current file. With a function name, set a break at the first
600 executable line of that function. If a second argument is
601 present, it is a string specifying an expression which must
602 evaluate to true before the breakpoint is honored.
603
604 The line number may be prefixed with a filename and a colon,
605 to specify a breakpoint in another file (probably one that
606 hasn't been loaded yet). The file is searched for on
607 sys.path; the .py suffix may be omitted.
608 """
Tim Peters2344fae2001-01-15 00:50:52 +0000609 if not arg:
610 if self.breaks: # There's at least one
Georg Brandl0d089622010-07-30 16:00:46 +0000611 self.message("Num Type Disp Enb Where")
Tim Peters2344fae2001-01-15 00:50:52 +0000612 for bp in bdb.Breakpoint.bpbynumber:
613 if bp:
Georg Brandl0d089622010-07-30 16:00:46 +0000614 self.message(bp.bpformat())
Tim Peters2344fae2001-01-15 00:50:52 +0000615 return
616 # parse arguments; comma has lowest precedence
617 # and cannot occur in filename
618 filename = None
619 lineno = None
620 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000621 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000622 if comma > 0:
623 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000624 cond = arg[comma+1:].lstrip()
625 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000626 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000627 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000628 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000629 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000630 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000631 f = self.lookupmodule(filename)
632 if not f:
Georg Brandl0d089622010-07-30 16:00:46 +0000633 self.error('%r not found from sys.path' % filename)
Tim Peters2344fae2001-01-15 00:50:52 +0000634 return
635 else:
636 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000637 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000638 try:
639 lineno = int(arg)
Georg Brandlf93390a2010-10-14 07:17:44 +0000640 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000641 self.error('Bad lineno: %s' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000642 return
643 else:
644 # no colon; can be lineno or function
645 try:
646 lineno = int(arg)
647 except ValueError:
648 try:
649 func = eval(arg,
650 self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +0000651 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000652 except:
653 func = arg
654 try:
Christian Heimesff737952007-11-27 10:40:20 +0000655 if hasattr(func, '__func__'):
656 func = func.__func__
Neal Norwitz221085d2007-02-25 20:55:47 +0000657 code = func.__code__
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000658 #use co_name to identify the bkpt (function names
659 #could be aliased, but co_name is invariant)
660 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000661 lineno = code.co_firstlineno
662 filename = code.co_filename
663 except:
664 # last thing to try
665 (ok, filename, ln) = self.lineinfo(arg)
666 if not ok:
Georg Brandl0d089622010-07-30 16:00:46 +0000667 self.error('The specified object %r is not a function '
668 'or was not found along sys.path.' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000669 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000670 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000671 lineno = int(ln)
672 if not filename:
673 filename = self.defaultFile()
674 # Check for reasonable breakpoint
675 line = self.checkline(filename, lineno)
676 if line:
677 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000678 err = self.set_break(filename, line, temporary, cond, funcname)
Georg Brandl0d089622010-07-30 16:00:46 +0000679 if err:
Berker Peksagad5ffd42014-07-12 18:24:32 +0300680 self.error(err)
Tim Peters2344fae2001-01-15 00:50:52 +0000681 else:
682 bp = self.get_breaks(filename, line)[-1]
Georg Brandl0d089622010-07-30 16:00:46 +0000683 self.message("Breakpoint %d at %s:%d" %
684 (bp.number, bp.file, bp.line))
Tim Peters2344fae2001-01-15 00:50:52 +0000685
686 # To be overridden in derived debuggers
687 def defaultFile(self):
688 """Produce a reasonable default."""
689 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000690 if filename == '<string>' and self.mainpyfile:
691 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000692 return filename
693
694 do_b = do_break
695
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100696 complete_break = _complete_location
697 complete_b = _complete_location
698
Tim Peters2344fae2001-01-15 00:50:52 +0000699 def do_tbreak(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000700 """tbreak [ ([filename:]lineno | function) [, condition] ]
701 Same arguments as break, but sets a temporary breakpoint: it
702 is automatically deleted when first hit.
703 """
Tim Peters2344fae2001-01-15 00:50:52 +0000704 self.do_break(arg, 1)
705
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100706 complete_tbreak = _complete_location
707
Tim Peters2344fae2001-01-15 00:50:52 +0000708 def lineinfo(self, identifier):
709 failed = (None, None, None)
710 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000711 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000712 if len(idstring) == 1:
713 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000714 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000715 elif len(idstring) == 3:
716 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000717 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000718 else:
719 return failed
720 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000721 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000722 # Protection for derived debuggers
723 if parts[0] == 'self':
724 del parts[0]
725 if len(parts) == 0:
726 return failed
727 # Best first guess at file to look at
728 fname = self.defaultFile()
729 if len(parts) == 1:
730 item = parts[0]
731 else:
732 # More than one part.
733 # First is module, second is method/class
734 f = self.lookupmodule(parts[0])
735 if f:
736 fname = f
737 item = parts[1]
738 answer = find_function(item, fname)
739 return answer or failed
740
741 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000742 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000743
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000744 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
745 line or EOF). Warning: testing is not comprehensive.
746 """
Georg Brandl1e30bd32010-07-30 07:21:26 +0000747 # this method should be callable before starting debugging, so default
748 # to "no globals" if there is no current frame
749 globs = self.curframe.f_globals if hasattr(self, 'curframe') else None
750 line = linecache.getline(filename, lineno, globs)
Tim Peters2344fae2001-01-15 00:50:52 +0000751 if not line:
Georg Brandl0d089622010-07-30 16:00:46 +0000752 self.message('End of file')
Tim Peters2344fae2001-01-15 00:50:52 +0000753 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000754 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000755 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000756 if (not line or (line[0] == '#') or
757 (line[:3] == '"""') or line[:3] == "'''"):
Georg Brandl0d089622010-07-30 16:00:46 +0000758 self.error('Blank or comment')
Tim Peters2344fae2001-01-15 00:50:52 +0000759 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000760 return lineno
761
762 def do_enable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000763 """enable bpnumber [bpnumber ...]
764 Enables the breakpoints given as a space separated list of
765 breakpoint numbers.
766 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000767 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000768 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000769 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000770 bp = self.get_bpbynumber(i)
771 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000772 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000773 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000774 bp.enable()
Georg Brandl0d089622010-07-30 16:00:46 +0000775 self.message('Enabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000776
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100777 complete_enable = _complete_bpnumber
778
Tim Peters2344fae2001-01-15 00:50:52 +0000779 def do_disable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000780 """disable bpnumber [bpnumber ...]
781 Disables the breakpoints given as a space separated list of
782 breakpoint numbers. Disabling a breakpoint means it cannot
783 cause the program to stop execution, but unlike clearing a
784 breakpoint, it remains in the list of breakpoints and can be
785 (re-)enabled.
786 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000787 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000788 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000789 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000790 bp = self.get_bpbynumber(i)
791 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000792 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000793 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000794 bp.disable()
Georg Brandl0d089622010-07-30 16:00:46 +0000795 self.message('Disabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000796
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100797 complete_disable = _complete_bpnumber
798
Tim Peters2344fae2001-01-15 00:50:52 +0000799 def do_condition(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000800 """condition bpnumber [condition]
801 Set a new condition for the breakpoint, an expression which
802 must evaluate to true before the breakpoint is honored. If
803 condition is absent, any existing condition is removed; i.e.,
804 the breakpoint is made unconditional.
805 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000806 args = arg.split(' ', 1)
Thomas Woutersb2137042007-02-01 18:02:27 +0000807 try:
Tim Peters2344fae2001-01-15 00:50:52 +0000808 cond = args[1]
Georg Brandl7410dd12010-07-30 12:01:20 +0000809 except IndexError:
Tim Peters2344fae2001-01-15 00:50:52 +0000810 cond = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000811 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000812 bp = self.get_bpbynumber(args[0].strip())
Georg Brandl0079ffc2013-10-14 16:08:15 +0200813 except IndexError:
814 self.error('Breakpoint number expected')
Georg Brandl7410dd12010-07-30 12:01:20 +0000815 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000816 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000817 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000818 bp.cond = cond
819 if not cond:
Georg Brandl0d089622010-07-30 16:00:46 +0000820 self.message('Breakpoint %d is now unconditional.' % bp.number)
Georg Brandl7410dd12010-07-30 12:01:20 +0000821 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000822 self.message('New condition set for breakpoint %d.' % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000823
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100824 complete_condition = _complete_bpnumber
825
Georg Brandl7410dd12010-07-30 12:01:20 +0000826 def do_ignore(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000827 """ignore bpnumber [count]
828 Set the ignore count for the given breakpoint number. If
829 count is omitted, the ignore count is set to 0. A breakpoint
830 becomes active when the ignore count is zero. When non-zero,
831 the count is decremented each time the breakpoint is reached
832 and the breakpoint is not disabled and any associated
833 condition evaluates to true.
834 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000835 args = arg.split()
Thomas Woutersb2137042007-02-01 18:02:27 +0000836 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000837 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000838 except:
839 count = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +0000840 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000841 bp = self.get_bpbynumber(args[0].strip())
Georg Brandl0079ffc2013-10-14 16:08:15 +0200842 except IndexError:
843 self.error('Breakpoint number expected')
Georg Brandl7410dd12010-07-30 12:01:20 +0000844 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000845 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000846 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000847 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000848 if count > 0:
Guido van Rossum08454592002-07-12 13:10:53 +0000849 if count > 1:
Georg Brandl0d089622010-07-30 16:00:46 +0000850 countstr = '%d crossings' % count
Tim Peters2344fae2001-01-15 00:50:52 +0000851 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000852 countstr = '1 crossing'
853 self.message('Will ignore next %s of breakpoint %d.' %
854 (countstr, bp.number))
Tim Peters2344fae2001-01-15 00:50:52 +0000855 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000856 self.message('Will stop next time breakpoint %d is reached.'
857 % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000858
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100859 complete_ignore = _complete_bpnumber
860
Tim Peters2344fae2001-01-15 00:50:52 +0000861 def do_clear(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000862 """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]]
863 With a space separated list of breakpoint numbers, clear
864 those breakpoints. Without argument, clear all breaks (but
865 first ask confirmation). With a filename:lineno argument,
866 clear all breaks at that line in that file.
867 """
Tim Peters2344fae2001-01-15 00:50:52 +0000868 if not arg:
869 try:
Guido van Rossumc5b6ab02007-05-27 09:19:52 +0000870 reply = input('Clear all breaks? ')
Tim Peters2344fae2001-01-15 00:50:52 +0000871 except EOFError:
872 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000873 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000874 if reply in ('y', 'yes'):
Georg Brandl7410dd12010-07-30 12:01:20 +0000875 bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp]
Tim Peters2344fae2001-01-15 00:50:52 +0000876 self.clear_all_breaks()
Georg Brandl7410dd12010-07-30 12:01:20 +0000877 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000878 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000879 return
880 if ':' in arg:
881 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000882 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000883 filename = arg[:i]
884 arg = arg[i+1:]
885 try:
886 lineno = int(arg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000887 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000888 err = "Invalid line number (%s)" % arg
889 else:
Georg Brandl7410dd12010-07-30 12:01:20 +0000890 bplist = self.get_breaks(filename, lineno)
Tim Peters2344fae2001-01-15 00:50:52 +0000891 err = self.clear_break(filename, lineno)
Georg Brandl7410dd12010-07-30 12:01:20 +0000892 if err:
Georg Brandl0d089622010-07-30 16:00:46 +0000893 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000894 else:
895 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000896 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000897 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000898 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000899 for i in numberlist:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000900 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000901 bp = self.get_bpbynumber(i)
902 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000903 self.error(err)
Tim Peters2344fae2001-01-15 00:50:52 +0000904 else:
Senthil Kumaran6f107042010-11-29 11:54:17 +0000905 self.clear_bpbynumber(i)
Georg Brandl0d089622010-07-30 16:00:46 +0000906 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000907 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
908
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100909 complete_clear = _complete_location
910 complete_cl = _complete_location
911
Tim Peters2344fae2001-01-15 00:50:52 +0000912 def do_where(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000913 """w(here)
914 Print a stack trace, with the most recent frame at the bottom.
915 An arrow indicates the "current frame", which determines the
916 context of most commands. 'bt' is an alias for this command.
917 """
Tim Peters2344fae2001-01-15 00:50:52 +0000918 self.print_stack_trace()
919 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000920 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000921
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000922 def _select_frame(self, number):
923 assert 0 <= number < len(self.stack)
924 self.curindex = number
925 self.curframe = self.stack[self.curindex][0]
926 self.curframe_locals = self.curframe.f_locals
927 self.print_stack_entry(self.stack[self.curindex])
928 self.lineno = None
929
Tim Peters2344fae2001-01-15 00:50:52 +0000930 def do_up(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000931 """u(p) [count]
932 Move the current frame count (default one) levels up in the
933 stack trace (to an older frame).
934 """
Tim Peters2344fae2001-01-15 00:50:52 +0000935 if self.curindex == 0:
Georg Brandl0d089622010-07-30 16:00:46 +0000936 self.error('Oldest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000937 return
938 try:
939 count = int(arg or 1)
940 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000941 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000942 return
943 if count < 0:
944 newframe = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000945 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000946 newframe = max(0, self.curindex - count)
947 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000948 do_u = do_up
949
950 def do_down(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000951 """d(own) [count]
952 Move the current frame count (default one) levels down in the
953 stack trace (to a newer frame).
954 """
Tim Peters2344fae2001-01-15 00:50:52 +0000955 if self.curindex + 1 == len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +0000956 self.error('Newest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000957 return
958 try:
959 count = int(arg or 1)
960 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000961 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000962 return
963 if count < 0:
964 newframe = len(self.stack) - 1
Tim Peters2344fae2001-01-15 00:50:52 +0000965 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000966 newframe = min(len(self.stack) - 1, self.curindex + count)
967 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000968 do_d = do_down
969
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000970 def do_until(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000971 """unt(il) [lineno]
972 Without argument, continue execution until the line with a
973 number greater than the current one is reached. With a line
974 number, continue execution until a line with a number greater
975 or equal to that is reached. In both cases, also stop when
976 the current frame returns.
977 """
Georg Brandl2dfec552010-07-30 08:43:32 +0000978 if arg:
979 try:
980 lineno = int(arg)
981 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000982 self.error('Error in argument: %r' % arg)
Georg Brandl2dfec552010-07-30 08:43:32 +0000983 return
984 if lineno <= self.curframe.f_lineno:
Georg Brandl0d089622010-07-30 16:00:46 +0000985 self.error('"until" line number is smaller than current '
986 'line number')
Georg Brandl2dfec552010-07-30 08:43:32 +0000987 return
988 else:
989 lineno = None
990 self.set_until(self.curframe, lineno)
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000991 return 1
992 do_unt = do_until
993
Tim Peters2344fae2001-01-15 00:50:52 +0000994 def do_step(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000995 """s(tep)
996 Execute the current line, stop at the first possible occasion
997 (either in a function that is called or in the current
998 function).
999 """
Tim Peters2344fae2001-01-15 00:50:52 +00001000 self.set_step()
1001 return 1
1002 do_s = do_step
1003
1004 def do_next(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001005 """n(ext)
1006 Continue execution until the next line in the current function
1007 is reached or it returns.
1008 """
Tim Peters2344fae2001-01-15 00:50:52 +00001009 self.set_next(self.curframe)
1010 return 1
1011 do_n = do_next
1012
Guido van Rossumd8faa362007-04-27 19:54:29 +00001013 def do_run(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001014 """run [args...]
1015 Restart the debugged python program. If a string is supplied
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001016 it is split with "shlex", and the result is used as the new
Georg Brandl0d089622010-07-30 16:00:46 +00001017 sys.argv. History, breakpoints, actions and debugger options
1018 are preserved. "restart" is an alias for "run".
1019 """
Guido van Rossumd8faa362007-04-27 19:54:29 +00001020 if arg:
1021 import shlex
1022 argv0 = sys.argv[0:1]
1023 sys.argv = shlex.split(arg)
1024 sys.argv[:0] = argv0
Georg Brandl0d089622010-07-30 16:00:46 +00001025 # this is caught in the main debugger loop
Guido van Rossumd8faa362007-04-27 19:54:29 +00001026 raise Restart
1027
1028 do_restart = do_run
1029
Tim Peters2344fae2001-01-15 00:50:52 +00001030 def do_return(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001031 """r(eturn)
1032 Continue execution until the current function returns.
1033 """
Tim Peters2344fae2001-01-15 00:50:52 +00001034 self.set_return(self.curframe)
1035 return 1
1036 do_r = do_return
1037
1038 def do_continue(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001039 """c(ont(inue))
1040 Continue execution, only stop when a breakpoint is encountered.
1041 """
Georg Brandl44f2b642010-12-04 16:00:47 +00001042 if not self.nosigint:
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001043 try:
Xavier de Gaye10e54ae2016-10-12 20:13:24 +02001044 Pdb._previous_sigint_handler = \
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001045 signal.signal(signal.SIGINT, self.sigint_handler)
1046 except ValueError:
1047 # ValueError happens when do_continue() is invoked from
1048 # a non-main thread in which case we just continue without
1049 # SIGINT set. Would printing a message here (once) make
1050 # sense?
1051 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001052 self.set_continue()
1053 return 1
1054 do_c = do_cont = do_continue
1055
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001056 def do_jump(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001057 """j(ump) lineno
1058 Set the next line that will be executed. Only available in
1059 the bottom-most frame. This lets you jump back and execute
1060 code again, or jump forward to skip code that you don't want
1061 to run.
1062
1063 It should be noted that not all jumps are allowed -- for
1064 instance it is not possible to jump into the middle of a
1065 for loop or out of a finally clause.
1066 """
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001067 if self.curindex + 1 != len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +00001068 self.error('You can only jump within the bottom frame')
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001069 return
1070 try:
1071 arg = int(arg)
1072 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +00001073 self.error("The 'jump' command requires a line number")
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001074 else:
1075 try:
1076 # Do the jump, fix up our copy of the stack, and display the
1077 # new position
1078 self.curframe.f_lineno = arg
1079 self.stack[self.curindex] = self.stack[self.curindex][0], arg
1080 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumb940e112007-01-10 16:19:56 +00001081 except ValueError as e:
Georg Brandl0d089622010-07-30 16:00:46 +00001082 self.error('Jump failed: %s' % e)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001083 do_j = do_jump
1084
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001085 def do_debug(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001086 """debug code
1087 Enter a recursive debugger that steps through the code
1088 argument (which is an arbitrary expression or statement to be
1089 executed in the current environment).
1090 """
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001091 sys.settrace(None)
1092 globals = self.curframe.f_globals
Benjamin Petersond23f8222009-04-05 19:13:16 +00001093 locals = self.curframe_locals
Guido van Rossum7736b5b2008-01-15 21:44:53 +00001094 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +00001095 p.prompt = "(%s) " % self.prompt.strip()
Georg Brandl0d089622010-07-30 16:00:46 +00001096 self.message("ENTERING RECURSIVE DEBUGGER")
Guido van Rossumed538d82003-04-09 19:36:34 +00001097 sys.call_tracing(p.run, (arg, globals, locals))
Georg Brandl0d089622010-07-30 16:00:46 +00001098 self.message("LEAVING RECURSIVE DEBUGGER")
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001099 sys.settrace(self.trace_dispatch)
1100 self.lastcmd = p.lastcmd
1101
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001102 complete_debug = _complete_expression
1103
Tim Peters2344fae2001-01-15 00:50:52 +00001104 def do_quit(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001105 """q(uit)\nexit
1106 Quit from the debugger. The program being executed is aborted.
1107 """
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001108 self._user_requested_quit = True
Tim Peters2344fae2001-01-15 00:50:52 +00001109 self.set_quit()
1110 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001111
Tim Peters2344fae2001-01-15 00:50:52 +00001112 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +00001113 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +00001114
Guido van Rossumeef26072003-01-13 21:13:55 +00001115 def do_EOF(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001116 """EOF
1117 Handles the receipt of EOF as a command.
1118 """
1119 self.message('')
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001120 self._user_requested_quit = True
Guido van Rossumeef26072003-01-13 21:13:55 +00001121 self.set_quit()
1122 return 1
1123
Tim Peters2344fae2001-01-15 00:50:52 +00001124 def do_args(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001125 """a(rgs)
1126 Print the argument list of the current function.
1127 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001128 co = self.curframe.f_code
1129 dict = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +00001130 n = co.co_argcount
1131 if co.co_flags & 4: n = n+1
1132 if co.co_flags & 8: n = n+1
1133 for i in range(n):
1134 name = co.co_varnames[i]
Georg Brandl0d089622010-07-30 16:00:46 +00001135 if name in dict:
1136 self.message('%s = %r' % (name, dict[name]))
1137 else:
1138 self.message('%s = *** undefined ***' % (name,))
Tim Peters2344fae2001-01-15 00:50:52 +00001139 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +00001140
Tim Peters2344fae2001-01-15 00:50:52 +00001141 def do_retval(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001142 """retval
1143 Print the return value for the last return of a function.
1144 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001145 if '__return__' in self.curframe_locals:
Georg Brandl0d089622010-07-30 16:00:46 +00001146 self.message(repr(self.curframe_locals['__return__']))
Tim Peters2344fae2001-01-15 00:50:52 +00001147 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001148 self.error('Not yet returned!')
Tim Peters2344fae2001-01-15 00:50:52 +00001149 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +00001150
Barry Warsaw210bd202002-11-05 22:40:20 +00001151 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +00001152 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +00001153 return eval(arg, self.curframe.f_globals, self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +00001154 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001155 exc_info = sys.exc_info()[:2]
1156 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Barry Warsaw210bd202002-11-05 22:40:20 +00001157 raise
Guido van Rossum2424f851998-09-11 22:50:09 +00001158
Georg Brandlcbc79c72010-12-04 16:21:42 +00001159 def _getval_except(self, arg, frame=None):
1160 try:
1161 if frame is None:
1162 return eval(arg, self.curframe.f_globals, self.curframe_locals)
1163 else:
1164 return eval(arg, frame.f_globals, frame.f_locals)
1165 except:
1166 exc_info = sys.exc_info()[:2]
1167 err = traceback.format_exception_only(*exc_info)[-1].strip()
1168 return _rstr('** raised %s **' % err)
1169
Barry Warsaw210bd202002-11-05 22:40:20 +00001170 def do_p(self, arg):
R David Murray78d692f2013-10-10 17:23:26 -04001171 """p expression
Georg Brandl0d089622010-07-30 16:00:46 +00001172 Print the value of the expression.
1173 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001174 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001175 self.message(repr(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001176 except:
1177 pass
1178
1179 def do_pp(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001180 """pp expression
1181 Pretty-print the value of the expression.
1182 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001183 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001184 self.message(pprint.pformat(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001185 except:
1186 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001187
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001188 complete_print = _complete_expression
1189 complete_p = _complete_expression
1190 complete_pp = _complete_expression
1191
Tim Peters2344fae2001-01-15 00:50:52 +00001192 def do_list(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001193 """l(ist) [first [,last] | .]
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001194
1195 List source code for the current file. Without arguments,
1196 list 11 lines around the current line or continue the previous
1197 listing. With . as argument, list 11 lines around the current
1198 line. With one argument, list 11 lines starting at that line.
1199 With two arguments, list the given range; if the second
1200 argument is less than the first, it is a count.
1201
1202 The current line in the current frame is indicated by "->".
1203 If an exception is being debugged, the line where the
1204 exception was originally raised or propagated is indicated by
1205 ">>", if it differs from the current line.
Georg Brandl0d089622010-07-30 16:00:46 +00001206 """
Tim Peters2344fae2001-01-15 00:50:52 +00001207 self.lastcmd = 'list'
1208 last = None
Georg Brandla91a94b2010-07-30 07:14:01 +00001209 if arg and arg != '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001210 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001211 if ',' in arg:
1212 first, last = arg.split(',')
1213 first = int(first.strip())
1214 last = int(last.strip())
Tim Peters2344fae2001-01-15 00:50:52 +00001215 if last < first:
Georg Brandl0d089622010-07-30 16:00:46 +00001216 # assume it's a count
Tim Peters2344fae2001-01-15 00:50:52 +00001217 last = first + last
1218 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001219 first = int(arg.strip())
1220 first = max(1, first - 5)
1221 except ValueError:
1222 self.error('Error in argument: %r' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001223 return
Georg Brandla91a94b2010-07-30 07:14:01 +00001224 elif self.lineno is None or arg == '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001225 first = max(1, self.curframe.f_lineno - 5)
1226 else:
1227 first = self.lineno + 1
1228 if last is None:
1229 last = first + 10
1230 filename = self.curframe.f_code.co_filename
1231 breaklist = self.get_file_breaks(filename)
1232 try:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001233 lines = linecache.getlines(filename, self.curframe.f_globals)
1234 self._print_lines(lines[first-1:last], first, breaklist,
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001235 self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001236 self.lineno = min(last, len(lines))
1237 if len(lines) < last:
1238 self.message('[EOF]')
Tim Peters2344fae2001-01-15 00:50:52 +00001239 except KeyboardInterrupt:
1240 pass
1241 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +00001242
Georg Brandle59ca2a2010-07-30 17:04:28 +00001243 def do_longlist(self, arg):
1244 """longlist | ll
1245 List the whole source code for the current function or frame.
1246 """
1247 filename = self.curframe.f_code.co_filename
1248 breaklist = self.get_file_breaks(filename)
1249 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001250 lines, lineno = getsourcelines(self.curframe)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001251 except OSError as err:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001252 self.error(err)
1253 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001254 self._print_lines(lines, lineno, breaklist, self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001255 do_ll = do_longlist
1256
1257 def do_source(self, arg):
1258 """source expression
1259 Try to get source code for the given object and display it.
1260 """
1261 try:
1262 obj = self._getval(arg)
1263 except:
1264 return
1265 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001266 lines, lineno = getsourcelines(obj)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001267 except (OSError, TypeError) as err:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001268 self.error(err)
1269 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001270 self._print_lines(lines, lineno)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001271
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001272 complete_source = _complete_expression
1273
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001274 def _print_lines(self, lines, start, breaks=(), frame=None):
Georg Brandle59ca2a2010-07-30 17:04:28 +00001275 """Print a range of lines."""
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001276 if frame:
1277 current_lineno = frame.f_lineno
1278 exc_lineno = self.tb_lineno.get(frame, -1)
1279 else:
1280 current_lineno = exc_lineno = -1
Georg Brandle59ca2a2010-07-30 17:04:28 +00001281 for lineno, line in enumerate(lines, start):
1282 s = str(lineno).rjust(3)
1283 if len(s) < 4:
1284 s += ' '
1285 if lineno in breaks:
1286 s += 'B'
1287 else:
1288 s += ' '
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001289 if lineno == current_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001290 s += '->'
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001291 elif lineno == exc_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001292 s += '>>'
1293 self.message(s + '\t' + line.rstrip())
1294
Tim Peters2344fae2001-01-15 00:50:52 +00001295 def do_whatis(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001296 """whatis arg
1297 Print the type of the argument.
1298 """
Tim Peters2344fae2001-01-15 00:50:52 +00001299 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001300 value = self._getval(arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001301 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001302 # _getval() already printed the error
Tim Peters2344fae2001-01-15 00:50:52 +00001303 return
1304 code = None
1305 # Is it a function?
Georg Brandl0d089622010-07-30 16:00:46 +00001306 try:
1307 code = value.__code__
1308 except Exception:
1309 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001310 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001311 self.message('Function %s' % code.co_name)
Tim Peters2344fae2001-01-15 00:50:52 +00001312 return
1313 # Is it an instance method?
Georg Brandl0d089622010-07-30 16:00:46 +00001314 try:
1315 code = value.__func__.__code__
1316 except Exception:
1317 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001318 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001319 self.message('Method %s' % code.co_name)
1320 return
1321 # Is it a class?
1322 if value.__class__ is type:
Serhiy Storchaka521e5862014-07-22 15:00:37 +03001323 self.message('Class %s.%s' % (value.__module__, value.__qualname__))
Tim Peters2344fae2001-01-15 00:50:52 +00001324 return
1325 # None of the above...
Georg Brandl0d089622010-07-30 16:00:46 +00001326 self.message(type(value))
Guido van Rossum8e2ec561993-07-29 09:37:38 +00001327
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001328 complete_whatis = _complete_expression
1329
Georg Brandlcbc79c72010-12-04 16:21:42 +00001330 def do_display(self, arg):
1331 """display [expression]
1332
1333 Display the value of the expression if it changed, each time execution
1334 stops in the current frame.
1335
1336 Without expression, list all display expressions for the current frame.
1337 """
1338 if not arg:
1339 self.message('Currently displaying:')
1340 for item in self.displaying.get(self.curframe, {}).items():
1341 self.message('%s: %r' % item)
1342 else:
1343 val = self._getval_except(arg)
1344 self.displaying.setdefault(self.curframe, {})[arg] = val
1345 self.message('display %s: %r' % (arg, val))
1346
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001347 complete_display = _complete_expression
1348
Georg Brandlcbc79c72010-12-04 16:21:42 +00001349 def do_undisplay(self, arg):
1350 """undisplay [expression]
1351
1352 Do not display the expression any more in the current frame.
1353
1354 Without expression, clear all display expressions for the current frame.
1355 """
1356 if arg:
1357 try:
1358 del self.displaying.get(self.curframe, {})[arg]
1359 except KeyError:
1360 self.error('not displaying %s' % arg)
1361 else:
1362 self.displaying.pop(self.curframe, None)
1363
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001364 def complete_undisplay(self, text, line, begidx, endidx):
1365 return [e for e in self.displaying.get(self.curframe, {})
1366 if e.startswith(text)]
1367
Georg Brandl1acb7462010-12-04 11:20:26 +00001368 def do_interact(self, arg):
1369 """interact
1370
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001371 Start an interactive interpreter whose global namespace
Georg Brandl1acb7462010-12-04 11:20:26 +00001372 contains all the (global and local) names found in the current scope.
1373 """
1374 ns = self.curframe.f_globals.copy()
1375 ns.update(self.curframe_locals)
1376 code.interact("*interactive*", local=ns)
1377
Tim Peters2344fae2001-01-15 00:50:52 +00001378 def do_alias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001379 """alias [name [command [parameter parameter ...] ]]
1380 Create an alias called 'name' that executes 'command'. The
1381 command must *not* be enclosed in quotes. Replaceable
1382 parameters can be indicated by %1, %2, and so on, while %* is
1383 replaced by all the parameters. If no command is given, the
1384 current alias for name is shown. If no name is given, all
1385 aliases are listed.
1386
1387 Aliases may be nested and can contain anything that can be
1388 legally typed at the pdb prompt. Note! You *can* override
1389 internal pdb commands with aliases! Those internal commands
1390 are then hidden until the alias is removed. Aliasing is
1391 recursively applied to the first word of the command line; all
1392 other words in the line are left alone.
1393
1394 As an example, here are two useful aliases (especially when
1395 placed in the .pdbrc file):
1396
1397 # Print instance variables (usage "pi classInst")
R David Murray78d692f2013-10-10 17:23:26 -04001398 alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])
Georg Brandl0d089622010-07-30 16:00:46 +00001399 # Print instance variables in self
1400 alias ps pi self
1401 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001402 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001403 if len(args) == 0:
Benjamin Petersonbe74a372009-09-11 21:17:13 +00001404 keys = sorted(self.aliases.keys())
Tim Peters2344fae2001-01-15 00:50:52 +00001405 for alias in keys:
Georg Brandl0d089622010-07-30 16:00:46 +00001406 self.message("%s = %s" % (alias, self.aliases[alias]))
Tim Peters2344fae2001-01-15 00:50:52 +00001407 return
Guido van Rossum08454592002-07-12 13:10:53 +00001408 if args[0] in self.aliases and len(args) == 1:
Georg Brandl0d089622010-07-30 16:00:46 +00001409 self.message("%s = %s" % (args[0], self.aliases[args[0]]))
Tim Peters2344fae2001-01-15 00:50:52 +00001410 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001411 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +00001412
Tim Peters2344fae2001-01-15 00:50:52 +00001413 def do_unalias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001414 """unalias name
1415 Delete the specified alias.
1416 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001417 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001418 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +00001419 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +00001420 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +00001421
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001422 def complete_unalias(self, text, line, begidx, endidx):
1423 return [a for a in self.aliases if a.startswith(text)]
1424
Georg Brandl0d089622010-07-30 16:00:46 +00001425 # List of all the commands making the program resume execution.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001426 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
1427 'do_quit', 'do_jump']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001428
Tim Peters2344fae2001-01-15 00:50:52 +00001429 # Print a traceback starting at the top stack frame.
1430 # The most recently entered frame is printed last;
1431 # this is different from dbx and gdb, but consistent with
1432 # the Python interpreter's stack trace.
1433 # It is also consistent with the up/down commands (which are
1434 # compatible with dbx and gdb: up moves towards 'main()'
1435 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +00001436
Tim Peters2344fae2001-01-15 00:50:52 +00001437 def print_stack_trace(self):
1438 try:
1439 for frame_lineno in self.stack:
1440 self.print_stack_entry(frame_lineno)
1441 except KeyboardInterrupt:
1442 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001443
Tim Peters2344fae2001-01-15 00:50:52 +00001444 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
1445 frame, lineno = frame_lineno
1446 if frame is self.curframe:
Georg Brandl0d089622010-07-30 16:00:46 +00001447 prefix = '> '
Tim Peters2344fae2001-01-15 00:50:52 +00001448 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001449 prefix = ' '
1450 self.message(prefix +
1451 self.format_stack_entry(frame_lineno, prompt_prefix))
Guido van Rossum2424f851998-09-11 22:50:09 +00001452
Georg Brandl0d089622010-07-30 16:00:46 +00001453 # Provide help
Guido van Rossum921c8241992-01-10 14:54:42 +00001454
Georg Brandl0d089622010-07-30 16:00:46 +00001455 def do_help(self, arg):
1456 """h(elp)
1457 Without argument, print the list of available commands.
1458 With a command name as argument, print help about that command.
1459 "help pdb" shows the full pdb documentation.
1460 "help exec" gives help on the ! command.
1461 """
1462 if not arg:
1463 return cmd.Cmd.do_help(self, arg)
1464 try:
1465 try:
1466 topic = getattr(self, 'help_' + arg)
1467 return topic()
1468 except AttributeError:
1469 command = getattr(self, 'do_' + arg)
1470 except AttributeError:
1471 self.error('No help for %r' % arg)
1472 else:
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001473 if sys.flags.optimize >= 2:
1474 self.error('No help for %r; please do not run Python with -OO '
1475 'if you need command help' % arg)
1476 return
Georg Brandl0d089622010-07-30 16:00:46 +00001477 self.message(command.__doc__.rstrip())
Guido van Rossum921c8241992-01-10 14:54:42 +00001478
Georg Brandl0d089622010-07-30 16:00:46 +00001479 do_h = do_help
Barry Warsaw210bd202002-11-05 22:40:20 +00001480
Tim Peters2344fae2001-01-15 00:50:52 +00001481 def help_exec(self):
Georg Brandl0d089622010-07-30 16:00:46 +00001482 """(!) statement
1483 Execute the (one-line) statement in the context of the current
1484 stack frame. The exclamation point can be omitted unless the
1485 first word of the statement resembles a debugger command. To
1486 assign to a global variable you must always prefix the command
1487 with a 'global' command, e.g.:
1488 (Pdb) global list_options; list_options = ['-l']
1489 (Pdb)
1490 """
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001491 self.message((self.help_exec.__doc__ or '').strip())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001492
Tim Peters2344fae2001-01-15 00:50:52 +00001493 def help_pdb(self):
1494 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001495
Georg Brandl0d089622010-07-30 16:00:46 +00001496 # other helper functions
1497
Tim Peters2344fae2001-01-15 00:50:52 +00001498 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001499 """Helper function for break/clear parsing -- may be overridden.
1500
1501 lookupmodule() translates (possibly incomplete) file or module name
1502 into an absolute file name.
1503 """
1504 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001505 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001506 f = os.path.join(sys.path[0], filename)
1507 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1508 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001509 root, ext = os.path.splitext(filename)
1510 if ext == '':
1511 filename = filename + '.py'
1512 if os.path.isabs(filename):
1513 return filename
1514 for dirname in sys.path:
1515 while os.path.islink(dirname):
1516 dirname = os.readlink(dirname)
1517 fullname = os.path.join(dirname, filename)
1518 if os.path.exists(fullname):
1519 return fullname
1520 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001521
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001522 def _runscript(self, filename):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001523 # The script has to run in __main__ namespace (or imports from
1524 # __main__ will break).
1525 #
1526 # So we clear up the __main__ and set several special variables
1527 # (this gets rid of pdb's globals and cleans old variables on restarts).
1528 import __main__
1529 __main__.__dict__.clear()
1530 __main__.__dict__.update({"__name__" : "__main__",
1531 "__file__" : filename,
1532 "__builtins__": __builtins__,
1533 })
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001534
1535 # When bdb sets tracing, a number of call and line events happens
1536 # BEFORE debugger even reaches user's code (and the exact sequence of
1537 # events depends on python version). So we take special measures to
1538 # avoid stopping before we reach the main script (see user_line and
1539 # user_call for details).
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001540 self._wait_for_mainpyfile = True
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001541 self.mainpyfile = self.canonic(filename)
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001542 self._user_requested_quit = False
Georg Brandld07ac642009-08-13 07:50:57 +00001543 with open(filename, "rb") as fp:
1544 statement = "exec(compile(%r, %r, 'exec'))" % \
1545 (fp.read(), self.mainpyfile)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001546 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001547
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001548# Collect all command help into docstring, if not run with -OO
Georg Brandl0d089622010-07-30 16:00:46 +00001549
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001550if __doc__ is not None:
1551 # unfortunately we can't guess this order from the class definition
1552 _help_order = [
1553 'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable',
1554 'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until',
1555 'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist',
R David Murray78d692f2013-10-10 17:23:26 -04001556 'args', 'p', 'pp', 'whatis', 'source', 'display', 'undisplay',
Georg Brandlcbc79c72010-12-04 16:21:42 +00001557 'interact', 'alias', 'unalias', 'debug', 'quit',
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001558 ]
Georg Brandl0d089622010-07-30 16:00:46 +00001559
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001560 for _command in _help_order:
1561 __doc__ += getattr(Pdb, 'do_' + _command).__doc__.strip() + '\n\n'
1562 __doc__ += Pdb.help_exec.__doc__
Georg Brandl0d089622010-07-30 16:00:46 +00001563
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001564 del _help_order, _command
1565
Georg Brandl0d089622010-07-30 16:00:46 +00001566
Guido van Rossum35771131992-09-08 11:59:04 +00001567# Simplified interface
1568
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001569def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001570 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001571
1572def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001573 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001574
1575def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001576 # B/W compatibility
1577 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001578
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001579def runcall(*args, **kwds):
1580 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001581
Guido van Rossumb6775db1994-08-01 11:34:53 +00001582def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001583 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001584
1585# Post-Mortem interface
1586
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001587def post_mortem(t=None):
1588 # handling the default
1589 if t is None:
1590 # sys.exc_info() returns (type, value, traceback) if an exception is
1591 # being handled, otherwise it returns None
1592 t = sys.exc_info()[2]
Georg Brandl0d089622010-07-30 16:00:46 +00001593 if t is None:
1594 raise ValueError("A valid traceback must be passed if no "
1595 "exception is being handled")
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001596
Tim Peters2344fae2001-01-15 00:50:52 +00001597 p = Pdb()
1598 p.reset()
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001599 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001600
1601def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001602 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001603
1604
1605# Main program for testing
1606
Guido van Rossum23efba41992-01-27 16:58:47 +00001607TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001608
Guido van Rossum921c8241992-01-10 14:54:42 +00001609def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001610 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001611
1612# print help
1613def help():
Georg Brandl02053ee2010-07-18 10:11:03 +00001614 import pydoc
1615 pydoc.pager(__doc__)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001616
Georg Brandle0230912010-07-30 08:29:39 +00001617_usage = """\
1618usage: pdb.py [-c command] ... pyfile [arg] ...
1619
1620Debug the Python program given by pyfile.
1621
1622Initial commands are read from .pdbrc files in your home directory
1623and in the current directory, if they exist. Commands supplied with
1624-c are executed after commands from .pdbrc files.
1625
1626To let the script run until an exception occurs, use "-c continue".
Georg Brandl2dfec552010-07-30 08:43:32 +00001627To let the script run up to a given line X in the debugged file, use
1628"-c 'until X'"."""
Georg Brandle0230912010-07-30 08:29:39 +00001629
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001630def main():
Georg Brandle0230912010-07-30 08:29:39 +00001631 import getopt
1632
1633 opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['--help', '--command='])
1634
1635 if not args:
1636 print(_usage)
Tim Peters2344fae2001-01-15 00:50:52 +00001637 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001638
Georg Brandle0230912010-07-30 08:29:39 +00001639 commands = []
1640 for opt, optarg in opts:
1641 if opt in ['-h', '--help']:
1642 print(_usage)
1643 sys.exit()
1644 elif opt in ['-c', '--command']:
1645 commands.append(optarg)
1646
1647 mainpyfile = args[0] # Get script filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001648 if not os.path.exists(mainpyfile):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001649 print('Error:', mainpyfile, 'does not exist')
Tim Peters2344fae2001-01-15 00:50:52 +00001650 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001651
Georg Brandle0230912010-07-30 08:29:39 +00001652 sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001653
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001654 # Replace pdb's dir with script's dir in front of module search path.
1655 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001656
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001657 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1658 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl3078df02009-05-05 09:11:31 +00001659 # changed by the user from the command line. There is a "restart" command
1660 # which allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001661 pdb = Pdb()
Georg Brandle0230912010-07-30 08:29:39 +00001662 pdb.rcLines.extend(commands)
Georg Brandl1e30bd32010-07-30 07:21:26 +00001663 while True:
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001664 try:
1665 pdb._runscript(mainpyfile)
1666 if pdb._user_requested_quit:
1667 break
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001668 print("The program finished and will be restarted")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001669 except Restart:
1670 print("Restarting", mainpyfile, "with arguments:")
Georg Brandle0230912010-07-30 08:29:39 +00001671 print("\t" + " ".join(args))
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001672 except SystemExit:
1673 # In most cases SystemExit does not warrant a post-mortem session.
Georg Brandle0230912010-07-30 08:29:39 +00001674 print("The program exited via sys.exit(). Exit status:", end=' ')
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001675 print(sys.exc_info()[1])
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001676 except SyntaxError:
1677 traceback.print_exc()
1678 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001679 except:
1680 traceback.print_exc()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001681 print("Uncaught exception. Entering post mortem debugging")
1682 print("Running 'cont' or 'step' will restart the program")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001683 t = sys.exc_info()[2]
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001684 pdb.interaction(None, t)
Georg Brandl3078df02009-05-05 09:11:31 +00001685 print("Post mortem debugger finished. The " + mainpyfile +
1686 " will be restarted")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001687
1688
1689# When invoked as main program, invoke the debugger on a script
Guido van Rossumd8faa362007-04-27 19:54:29 +00001690if __name__ == '__main__':
1691 import pdb
1692 pdb.main()