blob: 0e7609e43d4eea7f68f35345310df822c33c8037 [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
Ɓukasz Langa2eb6eca2016-09-09 22:21:17 -070055defined there can be overridden by the local file. This behavior can be
56disabled by passing the "readrc=False" argument to the Pdb constructor.
Georg Brandl02053ee2010-07-18 10:11:03 +000057
58Aside from aliases, the debugger is not directly programmable; but it
59is implemented as a class from which you can derive your own debugger
60class, which you can make as fancy as you like.
61
62
63Debugger commands
64=================
65
Georg Brandl02053ee2010-07-18 10:11:03 +000066"""
Georg Brandl0d089622010-07-30 16:00:46 +000067# NOTE: the actual command documentation is collected from docstrings of the
68# commands and is appended to __doc__ after the class has been defined.
Guido van Rossum921c8241992-01-10 14:54:42 +000069
Georg Brandl44f2b642010-12-04 16:00:47 +000070import os
71import re
Guido van Rossum921c8241992-01-10 14:54:42 +000072import sys
Guido van Rossum23efba41992-01-27 16:58:47 +000073import cmd
74import bdb
Georg Brandl0a9c3e92010-07-30 18:46:38 +000075import dis
Georg Brandl1acb7462010-12-04 11:20:26 +000076import code
Georg Brandl4c7c3c52012-03-10 22:36:48 +010077import glob
Barry Warsaw210bd202002-11-05 22:40:20 +000078import pprint
Georg Brandl44f2b642010-12-04 16:00:47 +000079import signal
Georg Brandle59ca2a2010-07-30 17:04:28 +000080import inspect
Georg Brandl1acb7462010-12-04 11:20:26 +000081import traceback
82import linecache
Guido van Rossumd8faa362007-04-27 19:54:29 +000083
84
85class Restart(Exception):
86 """Causes a debugger to be restarted for the debugged python program."""
87 pass
88
Skip Montanaro352674d2001-02-07 23:14:30 +000089__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
90 "post_mortem", "help"]
91
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000092def find_function(funcname, filename):
Thomas Wouters89f507f2006-12-13 04:49:30 +000093 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
Tim Peters2344fae2001-01-15 00:50:52 +000094 try:
95 fp = open(filename)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +020096 except OSError:
Tim Peters2344fae2001-01-15 00:50:52 +000097 return None
98 # consumer of this info expects the first line to be 1
Georg Brandl6e220552013-10-13 20:51:47 +020099 with fp:
100 for lineno, line in enumerate(fp, start=1):
101 if cre.match(line):
102 return funcname, filename, lineno
103 return None
Guido van Rossum921c8241992-01-10 14:54:42 +0000104
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000105def getsourcelines(obj):
106 lines, lineno = inspect.findsource(obj)
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000107 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000108 # must be a module frame: do not try to cut a block out of it
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000109 return lines, 1
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000110 elif inspect.ismodule(obj):
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000111 return lines, 1
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000112 return inspect.getblock(lines[lineno:]), lineno+1
Guido van Rossum921c8241992-01-10 14:54:42 +0000113
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000114def lasti2lineno(code, lasti):
115 linestarts = list(dis.findlinestarts(code))
116 linestarts.reverse()
117 for i, lineno in linestarts:
118 if lasti >= i:
119 return lineno
120 return 0
121
122
Georg Brandlcbc79c72010-12-04 16:21:42 +0000123class _rstr(str):
124 """String that doesn't quote its repr."""
125 def __repr__(self):
126 return self
127
128
Guido van Rossuma558e371994-11-10 22:27:35 +0000129# Interaction prompt line will separate file and call info from code
130# text using value of line_prefix string. A newline and arrow may
131# be to your liking. You can set it once pdb is imported using the
132# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +0000133# line_prefix = ': ' # Use this to get the old situation back
134line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +0000135
Guido van Rossum23efba41992-01-27 16:58:47 +0000136class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +0000137
Xavier de Gaye10e54ae2016-10-12 20:13:24 +0200138 _previous_sigint_handler = None
139
Georg Brandl44f2b642010-12-04 16:00:47 +0000140 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None,
Ɓukasz Langa2eb6eca2016-09-09 22:21:17 -0700141 nosigint=False, readrc=True):
Georg Brandl243ad662009-05-05 09:00:19 +0000142 bdb.Bdb.__init__(self, skip=skip)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000143 cmd.Cmd.__init__(self, completekey, stdin, stdout)
144 if stdout:
145 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000146 self.prompt = '(Pdb) '
147 self.aliases = {}
Georg Brandlcbc79c72010-12-04 16:21:42 +0000148 self.displaying = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000149 self.mainpyfile = ''
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000150 self._wait_for_mainpyfile = False
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000151 self.tb_lineno = {}
Tim Peters2344fae2001-01-15 00:50:52 +0000152 # Try to load readline if it exists
153 try:
154 import readline
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100155 # remove some common file name delimiters
156 readline.set_completer_delims(' \t\n`@#$%^&*()=+[{]}\\|;:\'",<>?')
Brett Cannoncd171c82013-07-04 17:43:24 -0400157 except ImportError:
Tim Peters2344fae2001-01-15 00:50:52 +0000158 pass
Georg Brandl44f2b642010-12-04 16:00:47 +0000159 self.allow_kbdint = False
160 self.nosigint = nosigint
Guido van Rossum2424f851998-09-11 22:50:09 +0000161
Tim Peters2344fae2001-01-15 00:50:52 +0000162 # Read $HOME/.pdbrc and ./.pdbrc
163 self.rcLines = []
Ɓukasz Langa2eb6eca2016-09-09 22:21:17 -0700164 if readrc:
165 if 'HOME' in os.environ:
166 envHome = os.environ['HOME']
167 try:
168 with open(os.path.join(envHome, ".pdbrc")) as rcFile:
169 self.rcLines.extend(rcFile)
170 except OSError:
171 pass
Tim Peters2344fae2001-01-15 00:50:52 +0000172 try:
Ɓukasz Langa2eb6eca2016-09-09 22:21:17 -0700173 with open(".pdbrc") as rcFile:
Florent Xicluna7dde7922010-09-03 19:52:03 +0000174 self.rcLines.extend(rcFile)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200175 except OSError:
Tim Peters2344fae2001-01-15 00:50:52 +0000176 pass
Guido van Rossum23efba41992-01-27 16:58:47 +0000177
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000178 self.commands = {} # associates a command list to breakpoint numbers
Benjamin Petersond23f8222009-04-05 19:13:16 +0000179 self.commands_doprompt = {} # for each bp num, tells if the prompt
180 # must be disp. after execing the cmd list
181 self.commands_silent = {} # for each bp num, tells if the stack trace
182 # must be disp. after execing the cmd list
183 self.commands_defining = False # True while in the process of defining
184 # a command list
185 self.commands_bnum = None # The breakpoint number for which we are
186 # defining a list
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000187
Georg Brandl44f2b642010-12-04 16:00:47 +0000188 def sigint_handler(self, signum, frame):
189 if self.allow_kbdint:
190 raise KeyboardInterrupt
191 self.message("\nProgram interrupted. (Use 'cont' to resume).")
192 self.set_step()
193 self.set_trace(frame)
Georg Brandl44f2b642010-12-04 16:00:47 +0000194
Tim Peters2344fae2001-01-15 00:50:52 +0000195 def reset(self):
196 bdb.Bdb.reset(self)
197 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000198
Tim Peters2344fae2001-01-15 00:50:52 +0000199 def forget(self):
200 self.lineno = None
201 self.stack = []
202 self.curindex = 0
203 self.curframe = None
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000204 self.tb_lineno.clear()
Guido van Rossum2424f851998-09-11 22:50:09 +0000205
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000206 def setup(self, f, tb):
Tim Peters2344fae2001-01-15 00:50:52 +0000207 self.forget()
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000208 self.stack, self.curindex = self.get_stack(f, tb)
209 while tb:
210 # when setting up post-mortem debugging with a traceback, save all
211 # the original line numbers to be displayed along the current line
212 # numbers (which can be different, e.g. due to finally clauses)
213 lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti)
214 self.tb_lineno[tb.tb_frame] = lineno
215 tb = tb.tb_next
Tim Peters2344fae2001-01-15 00:50:52 +0000216 self.curframe = self.stack[self.curindex][0]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000217 # The f_locals dictionary is updated from the actual frame
218 # locals whenever the .f_locals accessor is called, so we
219 # cache it here to ensure that modifications are not overwritten.
220 self.curframe_locals = self.curframe.f_locals
Georg Brandle0230912010-07-30 08:29:39 +0000221 return self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000222
Tim Peters2344fae2001-01-15 00:50:52 +0000223 # Can be executed earlier than 'setup' if desired
224 def execRcLines(self):
Georg Brandle0230912010-07-30 08:29:39 +0000225 if not self.rcLines:
226 return
227 # local copy because of recursion
228 rcLines = self.rcLines
229 rcLines.reverse()
230 # execute every line only once
231 self.rcLines = []
232 while rcLines:
233 line = rcLines.pop().strip()
234 if line and line[0] != '#':
235 if self.onecmd(line):
236 # if onecmd returns True, the command wants to exit
237 # from the interaction, save leftover rc lines
238 # to execute before next interaction
239 self.rcLines += reversed(rcLines)
240 return True
Guido van Rossum2424f851998-09-11 22:50:09 +0000241
Tim Peters280488b2002-08-23 18:19:30 +0000242 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000243
244 def user_call(self, frame, argument_list):
245 """This method is called when there is the remote possibility
246 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000247 if self._wait_for_mainpyfile:
248 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000249 if self.stop_here(frame):
Georg Brandl0d089622010-07-30 16:00:46 +0000250 self.message('--Call--')
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000251 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000252
Tim Peters2344fae2001-01-15 00:50:52 +0000253 def user_line(self, frame):
254 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000255 if self._wait_for_mainpyfile:
256 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000257 or frame.f_lineno <= 0):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000258 return
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000259 self._wait_for_mainpyfile = False
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000260 if self.bp_commands(frame):
261 self.interaction(frame, None)
262
Georg Brandle0230912010-07-30 08:29:39 +0000263 def bp_commands(self, frame):
Georg Brandl3078df02009-05-05 09:11:31 +0000264 """Call every command that was set for the current active breakpoint
265 (if there is one).
266
267 Returns True if the normal interaction function must be called,
268 False otherwise."""
269 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
270 if getattr(self, "currentbp", False) and \
271 self.currentbp in self.commands:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000272 currentbp = self.currentbp
273 self.currentbp = 0
274 lastcmd_back = self.lastcmd
275 self.setup(frame, None)
276 for line in self.commands[currentbp]:
277 self.onecmd(line)
278 self.lastcmd = lastcmd_back
279 if not self.commands_silent[currentbp]:
280 self.print_stack_entry(self.stack[self.curindex])
281 if self.commands_doprompt[currentbp]:
Georg Brandl44f2b642010-12-04 16:00:47 +0000282 self._cmdloop()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000283 self.forget()
284 return
285 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000286
Tim Peters2344fae2001-01-15 00:50:52 +0000287 def user_return(self, frame, return_value):
288 """This function is called when a return trap is set here."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000289 if self._wait_for_mainpyfile:
290 return
Tim Peters2344fae2001-01-15 00:50:52 +0000291 frame.f_locals['__return__'] = return_value
Georg Brandl0d089622010-07-30 16:00:46 +0000292 self.message('--Return--')
Tim Peters2344fae2001-01-15 00:50:52 +0000293 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000294
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000295 def user_exception(self, frame, exc_info):
Tim Peters2344fae2001-01-15 00:50:52 +0000296 """This function is called if an exception occurs,
297 but only if we are to stop at or just below this level."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000298 if self._wait_for_mainpyfile:
299 return
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000300 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000301 frame.f_locals['__exception__'] = exc_type, exc_value
Guido van Rossum8820c232013-11-21 11:30:06 -0800302
303 # An 'Internal StopIteration' exception is an exception debug event
304 # issued by the interpreter when handling a subgenerator run with
Martin Panter46f50722016-05-26 05:35:26 +0000305 # 'yield from' or a generator controlled by a for loop. No exception has
Berker Peksagf23530f2014-10-19 18:04:38 +0300306 # actually occurred in this case. The debugger uses this debug event to
Guido van Rossum8820c232013-11-21 11:30:06 -0800307 # stop when the debuggee is returning from such generators.
308 prefix = 'Internal ' if (not exc_traceback
309 and exc_type is StopIteration) else ''
310 self.message('%s%s' % (prefix,
311 traceback.format_exception_only(exc_type, exc_value)[-1].strip()))
Tim Peters2344fae2001-01-15 00:50:52 +0000312 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000313
Tim Peters2344fae2001-01-15 00:50:52 +0000314 # General interaction function
Georg Brandl44f2b642010-12-04 16:00:47 +0000315 def _cmdloop(self):
316 while True:
317 try:
318 # keyboard interrupts allow for an easy way to cancel
319 # the current command, so allow them during interactive input
320 self.allow_kbdint = True
321 self.cmdloop()
322 self.allow_kbdint = False
323 break
324 except KeyboardInterrupt:
325 self.message('--KeyboardInterrupt--')
Tim Peters2344fae2001-01-15 00:50:52 +0000326
Georg Brandlcbc79c72010-12-04 16:21:42 +0000327 # Called before loop, handles display expressions
328 def preloop(self):
329 displaying = self.displaying.get(self.curframe)
330 if displaying:
331 for expr, oldvalue in displaying.items():
332 newvalue = self._getval_except(expr)
333 # check for identity first; this prevents custom __eq__ to
334 # be called at every loop, and also prevents instances whose
335 # fields are changed to be displayed
336 if newvalue is not oldvalue and newvalue != oldvalue:
337 displaying[expr] = newvalue
338 self.message('display %s: %r [old: %r]' %
339 (expr, newvalue, oldvalue))
340
Tim Peters2344fae2001-01-15 00:50:52 +0000341 def interaction(self, frame, traceback):
Xavier de Gaye10e54ae2016-10-12 20:13:24 +0200342 # Restore the previous signal handler at the Pdb prompt.
343 if Pdb._previous_sigint_handler:
344 signal.signal(signal.SIGINT, Pdb._previous_sigint_handler)
345 Pdb._previous_sigint_handler = None
Georg Brandle0230912010-07-30 08:29:39 +0000346 if self.setup(frame, traceback):
347 # no interaction desired at this time (happens if .pdbrc contains
348 # a command like "continue")
349 self.forget()
350 return
Tim Peters2344fae2001-01-15 00:50:52 +0000351 self.print_stack_entry(self.stack[self.curindex])
Georg Brandl44f2b642010-12-04 16:00:47 +0000352 self._cmdloop()
Tim Peters2344fae2001-01-15 00:50:52 +0000353 self.forget()
354
Benjamin Petersond23f8222009-04-05 19:13:16 +0000355 def displayhook(self, obj):
356 """Custom displayhook for the exec in default(), which prevents
357 assignment of the _ variable in the builtins.
358 """
Georg Brandl9fa2e022009-09-16 16:40:45 +0000359 # reproduce the behavior of the standard displayhook, not printing None
360 if obj is not None:
Georg Brandl0d089622010-07-30 16:00:46 +0000361 self.message(repr(obj))
Benjamin Petersond23f8222009-04-05 19:13:16 +0000362
Tim Peters2344fae2001-01-15 00:50:52 +0000363 def default(self, line):
364 if line[:1] == '!': line = line[1:]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000365 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000366 globals = self.curframe.f_globals
367 try:
368 code = compile(line + '\n', '<stdin>', 'single')
Christian Heimes679db4a2008-01-18 09:56:22 +0000369 save_stdout = sys.stdout
370 save_stdin = sys.stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000371 save_displayhook = sys.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000372 try:
373 sys.stdin = self.stdin
374 sys.stdout = self.stdout
Benjamin Petersond23f8222009-04-05 19:13:16 +0000375 sys.displayhook = self.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000376 exec(code, globals, locals)
377 finally:
378 sys.stdout = save_stdout
379 sys.stdin = save_stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000380 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000381 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000382 exc_info = sys.exc_info()[:2]
383 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000384
385 def precmd(self, line):
386 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000387 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000388 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000389 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000390 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000391 line = self.aliases[args[0]]
392 ii = 1
393 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000394 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000395 tmpArg)
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000396 ii += 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000397 line = line.replace("%*", ' '.join(args[1:]))
398 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000399 # split into ';;' separated commands
400 # unless it's an alias command
401 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000402 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000403 if marker >= 0:
404 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000405 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000406 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000407 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000408 return line
409
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000410 def onecmd(self, line):
411 """Interpret the argument as though it had been typed in response
412 to the prompt.
413
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000414 Checks whether this line is typed at the normal prompt or in
415 a breakpoint command list definition.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000416 """
417 if not self.commands_defining:
418 return cmd.Cmd.onecmd(self, line)
419 else:
420 return self.handle_command_def(line)
421
Georg Brandlb90ffd82010-07-30 22:20:16 +0000422 def handle_command_def(self, line):
Georg Brandl44f8bf92010-07-30 08:54:49 +0000423 """Handles one command line during command list definition."""
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000424 cmd, arg, line = self.parseline(line)
Georg Brandl44f8bf92010-07-30 08:54:49 +0000425 if not cmd:
426 return
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000427 if cmd == 'silent':
428 self.commands_silent[self.commands_bnum] = True
429 return # continue to handle other cmd def in the cmd list
430 elif cmd == 'end':
431 self.cmdqueue = []
432 return 1 # end of cmd list
433 cmdlist = self.commands[self.commands_bnum]
Georg Brandl44f8bf92010-07-30 08:54:49 +0000434 if arg:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000435 cmdlist.append(cmd+' '+arg)
436 else:
437 cmdlist.append(cmd)
438 # Determine if we must stop
439 try:
440 func = getattr(self, 'do_' + cmd)
441 except AttributeError:
442 func = self.default
Georg Brandl3078df02009-05-05 09:11:31 +0000443 # one of the resuming commands
444 if func.__name__ in self.commands_resuming:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000445 self.commands_doprompt[self.commands_bnum] = False
446 self.cmdqueue = []
447 return 1
448 return
449
Georg Brandl0d089622010-07-30 16:00:46 +0000450 # interface abstraction functions
451
452 def message(self, msg):
453 print(msg, file=self.stdout)
454
455 def error(self, msg):
456 print('***', msg, file=self.stdout)
457
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100458 # Generic completion functions. Individual complete_foo methods can be
459 # assigned below to one of these functions.
460
461 def _complete_location(self, text, line, begidx, endidx):
462 # Complete a file/module/function location for break/tbreak/clear.
463 if line.strip().endswith((':', ',')):
464 # Here comes a line number or a condition which we can't complete.
465 return []
466 # First, try to find matching functions (i.e. expressions).
467 try:
468 ret = self._complete_expression(text, line, begidx, endidx)
469 except Exception:
470 ret = []
471 # Then, try to complete file names as well.
472 globs = glob.glob(text + '*')
473 for fn in globs:
474 if os.path.isdir(fn):
475 ret.append(fn + '/')
476 elif os.path.isfile(fn) and fn.lower().endswith(('.py', '.pyw')):
477 ret.append(fn + ':')
478 return ret
479
480 def _complete_bpnumber(self, text, line, begidx, endidx):
481 # Complete a breakpoint number. (This would be more helpful if we could
482 # display additional info along with the completions, such as file/line
483 # of the breakpoint.)
484 return [str(i) for i, bp in enumerate(bdb.Breakpoint.bpbynumber)
485 if bp is not None and str(i).startswith(text)]
486
487 def _complete_expression(self, text, line, begidx, endidx):
488 # Complete an arbitrary expression.
489 if not self.curframe:
490 return []
491 # Collect globals and locals. It is usually not really sensible to also
492 # complete builtins, and they clutter the namespace quite heavily, so we
493 # leave them out.
Serhiy Storchakada084702019-03-27 08:02:28 +0200494 ns = {**self.curframe.f_globals, **self.curframe_locals}
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100495 if '.' in text:
496 # Walk an attribute chain up to the last part, similar to what
497 # rlcompleter does. This will bail if any of the parts are not
498 # simple attribute access, which is what we want.
499 dotted = text.split('.')
500 try:
501 obj = ns[dotted[0]]
502 for part in dotted[1:-1]:
503 obj = getattr(obj, part)
504 except (KeyError, AttributeError):
505 return []
506 prefix = '.'.join(dotted[:-1]) + '.'
507 return [prefix + n for n in dir(obj) if n.startswith(dotted[-1])]
508 else:
509 # Complete a simple name.
510 return [n for n in ns.keys() if n.startswith(text)]
511
Tim Peters2344fae2001-01-15 00:50:52 +0000512 # Command definitions, called by cmdloop()
513 # The argument is the remaining string on the command line
514 # Return true to exit from the command loop
515
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000516 def do_commands(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000517 """commands [bpnumber]
518 (com) ...
519 (com) end
520 (Pdb)
Georg Brandl3078df02009-05-05 09:11:31 +0000521
Georg Brandl0d089622010-07-30 16:00:46 +0000522 Specify a list of commands for breakpoint number bpnumber.
523 The commands themselves are entered on the following lines.
524 Type a line containing just 'end' to terminate the commands.
525 The commands are executed when the breakpoint is hit.
526
527 To remove all commands from a breakpoint, type commands and
528 follow it immediately with end; that is, give no commands.
529
530 With no bpnumber argument, commands refers to the last
531 breakpoint set.
532
533 You can use breakpoint commands to start your program up
534 again. Simply use the continue command, or step, or any other
535 command that resumes execution.
536
537 Specifying any command resuming execution (currently continue,
538 step, next, return, jump, quit and their abbreviations)
539 terminates the command list (as if that command was
540 immediately followed by end). This is because any time you
541 resume execution (even with a simple next or step), you may
542 encounter another breakpoint -- which could have its own
543 command list, leading to ambiguities about which list to
544 execute.
545
546 If you use the 'silent' command in the command list, the usual
547 message about stopping at a breakpoint is not printed. This
548 may be desirable for breakpoints that are to print a specific
549 message and then continue. If none of the other commands
550 print anything, you will see no sign that the breakpoint was
551 reached.
552 """
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000553 if not arg:
Georg Brandl7410dd12010-07-30 12:01:20 +0000554 bnum = len(bdb.Breakpoint.bpbynumber) - 1
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000555 else:
556 try:
557 bnum = int(arg)
558 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000559 self.error("Usage: commands [bnum]\n ...\n end")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000560 return
561 self.commands_bnum = bnum
Georg Brandlb90ffd82010-07-30 22:20:16 +0000562 # Save old definitions for the case of a keyboard interrupt.
563 if bnum in self.commands:
564 old_command_defs = (self.commands[bnum],
565 self.commands_doprompt[bnum],
566 self.commands_silent[bnum])
567 else:
568 old_command_defs = None
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000569 self.commands[bnum] = []
570 self.commands_doprompt[bnum] = True
571 self.commands_silent[bnum] = False
Georg Brandlb90ffd82010-07-30 22:20:16 +0000572
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000573 prompt_back = self.prompt
574 self.prompt = '(com) '
575 self.commands_defining = True
Georg Brandl44f8bf92010-07-30 08:54:49 +0000576 try:
577 self.cmdloop()
Georg Brandlb90ffd82010-07-30 22:20:16 +0000578 except KeyboardInterrupt:
579 # Restore old definitions.
580 if old_command_defs:
581 self.commands[bnum] = old_command_defs[0]
582 self.commands_doprompt[bnum] = old_command_defs[1]
583 self.commands_silent[bnum] = old_command_defs[2]
584 else:
585 del self.commands[bnum]
586 del self.commands_doprompt[bnum]
587 del self.commands_silent[bnum]
588 self.error('command definition aborted, old commands restored')
Georg Brandl44f8bf92010-07-30 08:54:49 +0000589 finally:
590 self.commands_defining = False
591 self.prompt = prompt_back
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000592
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100593 complete_commands = _complete_bpnumber
594
Tim Peters2344fae2001-01-15 00:50:52 +0000595 def do_break(self, arg, temporary = 0):
Georg Brandl0d089622010-07-30 16:00:46 +0000596 """b(reak) [ ([filename:]lineno | function) [, condition] ]
597 Without argument, list all breaks.
598
599 With a line number argument, set a break at this line in the
600 current file. With a function name, set a break at the first
601 executable line of that function. If a second argument is
602 present, it is a string specifying an expression which must
603 evaluate to true before the breakpoint is honored.
604
605 The line number may be prefixed with a filename and a colon,
606 to specify a breakpoint in another file (probably one that
607 hasn't been loaded yet). The file is searched for on
608 sys.path; the .py suffix may be omitted.
609 """
Tim Peters2344fae2001-01-15 00:50:52 +0000610 if not arg:
611 if self.breaks: # There's at least one
Georg Brandl0d089622010-07-30 16:00:46 +0000612 self.message("Num Type Disp Enb Where")
Tim Peters2344fae2001-01-15 00:50:52 +0000613 for bp in bdb.Breakpoint.bpbynumber:
614 if bp:
Georg Brandl0d089622010-07-30 16:00:46 +0000615 self.message(bp.bpformat())
Tim Peters2344fae2001-01-15 00:50:52 +0000616 return
617 # parse arguments; comma has lowest precedence
618 # and cannot occur in filename
619 filename = None
620 lineno = None
621 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000622 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000623 if comma > 0:
624 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000625 cond = arg[comma+1:].lstrip()
626 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000627 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000628 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000629 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000630 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000631 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000632 f = self.lookupmodule(filename)
633 if not f:
Georg Brandl0d089622010-07-30 16:00:46 +0000634 self.error('%r not found from sys.path' % filename)
Tim Peters2344fae2001-01-15 00:50:52 +0000635 return
636 else:
637 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000638 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000639 try:
640 lineno = int(arg)
Georg Brandlf93390a2010-10-14 07:17:44 +0000641 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000642 self.error('Bad lineno: %s' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000643 return
644 else:
645 # no colon; can be lineno or function
646 try:
647 lineno = int(arg)
648 except ValueError:
649 try:
650 func = eval(arg,
651 self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +0000652 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000653 except:
654 func = arg
655 try:
Christian Heimesff737952007-11-27 10:40:20 +0000656 if hasattr(func, '__func__'):
657 func = func.__func__
Neal Norwitz221085d2007-02-25 20:55:47 +0000658 code = func.__code__
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000659 #use co_name to identify the bkpt (function names
660 #could be aliased, but co_name is invariant)
661 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000662 lineno = code.co_firstlineno
663 filename = code.co_filename
664 except:
665 # last thing to try
666 (ok, filename, ln) = self.lineinfo(arg)
667 if not ok:
Georg Brandl0d089622010-07-30 16:00:46 +0000668 self.error('The specified object %r is not a function '
669 'or was not found along sys.path.' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000670 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000671 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000672 lineno = int(ln)
673 if not filename:
674 filename = self.defaultFile()
675 # Check for reasonable breakpoint
676 line = self.checkline(filename, lineno)
677 if line:
678 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000679 err = self.set_break(filename, line, temporary, cond, funcname)
Georg Brandl0d089622010-07-30 16:00:46 +0000680 if err:
Berker Peksagad5ffd42014-07-12 18:24:32 +0300681 self.error(err)
Tim Peters2344fae2001-01-15 00:50:52 +0000682 else:
683 bp = self.get_breaks(filename, line)[-1]
Georg Brandl0d089622010-07-30 16:00:46 +0000684 self.message("Breakpoint %d at %s:%d" %
685 (bp.number, bp.file, bp.line))
Tim Peters2344fae2001-01-15 00:50:52 +0000686
687 # To be overridden in derived debuggers
688 def defaultFile(self):
689 """Produce a reasonable default."""
690 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000691 if filename == '<string>' and self.mainpyfile:
692 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000693 return filename
694
695 do_b = do_break
696
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100697 complete_break = _complete_location
698 complete_b = _complete_location
699
Tim Peters2344fae2001-01-15 00:50:52 +0000700 def do_tbreak(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000701 """tbreak [ ([filename:]lineno | function) [, condition] ]
702 Same arguments as break, but sets a temporary breakpoint: it
703 is automatically deleted when first hit.
704 """
Tim Peters2344fae2001-01-15 00:50:52 +0000705 self.do_break(arg, 1)
706
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100707 complete_tbreak = _complete_location
708
Tim Peters2344fae2001-01-15 00:50:52 +0000709 def lineinfo(self, identifier):
710 failed = (None, None, None)
711 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000712 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000713 if len(idstring) == 1:
714 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000715 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000716 elif len(idstring) == 3:
717 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000718 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000719 else:
720 return failed
721 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000722 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000723 # Protection for derived debuggers
724 if parts[0] == 'self':
725 del parts[0]
726 if len(parts) == 0:
727 return failed
728 # Best first guess at file to look at
729 fname = self.defaultFile()
730 if len(parts) == 1:
731 item = parts[0]
732 else:
733 # More than one part.
734 # First is module, second is method/class
735 f = self.lookupmodule(parts[0])
736 if f:
737 fname = f
738 item = parts[1]
739 answer = find_function(item, fname)
740 return answer or failed
741
742 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000743 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000744
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000745 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
746 line or EOF). Warning: testing is not comprehensive.
747 """
Georg Brandl1e30bd32010-07-30 07:21:26 +0000748 # this method should be callable before starting debugging, so default
749 # to "no globals" if there is no current frame
750 globs = self.curframe.f_globals if hasattr(self, 'curframe') else None
751 line = linecache.getline(filename, lineno, globs)
Tim Peters2344fae2001-01-15 00:50:52 +0000752 if not line:
Georg Brandl0d089622010-07-30 16:00:46 +0000753 self.message('End of file')
Tim Peters2344fae2001-01-15 00:50:52 +0000754 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000755 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000756 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000757 if (not line or (line[0] == '#') or
758 (line[:3] == '"""') or line[:3] == "'''"):
Georg Brandl0d089622010-07-30 16:00:46 +0000759 self.error('Blank or comment')
Tim Peters2344fae2001-01-15 00:50:52 +0000760 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000761 return lineno
762
763 def do_enable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000764 """enable bpnumber [bpnumber ...]
765 Enables the breakpoints given as a space separated list of
766 breakpoint numbers.
767 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000768 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000769 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000770 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000771 bp = self.get_bpbynumber(i)
772 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000773 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000774 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000775 bp.enable()
Georg Brandl0d089622010-07-30 16:00:46 +0000776 self.message('Enabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000777
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100778 complete_enable = _complete_bpnumber
779
Tim Peters2344fae2001-01-15 00:50:52 +0000780 def do_disable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000781 """disable bpnumber [bpnumber ...]
782 Disables the breakpoints given as a space separated list of
783 breakpoint numbers. Disabling a breakpoint means it cannot
784 cause the program to stop execution, but unlike clearing a
785 breakpoint, it remains in the list of breakpoints and can be
786 (re-)enabled.
787 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000788 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000789 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000790 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000791 bp = self.get_bpbynumber(i)
792 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000793 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000794 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000795 bp.disable()
Georg Brandl0d089622010-07-30 16:00:46 +0000796 self.message('Disabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000797
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100798 complete_disable = _complete_bpnumber
799
Tim Peters2344fae2001-01-15 00:50:52 +0000800 def do_condition(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000801 """condition bpnumber [condition]
802 Set a new condition for the breakpoint, an expression which
803 must evaluate to true before the breakpoint is honored. If
804 condition is absent, any existing condition is removed; i.e.,
805 the breakpoint is made unconditional.
806 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000807 args = arg.split(' ', 1)
Thomas Woutersb2137042007-02-01 18:02:27 +0000808 try:
Tim Peters2344fae2001-01-15 00:50:52 +0000809 cond = args[1]
Georg Brandl7410dd12010-07-30 12:01:20 +0000810 except IndexError:
Tim Peters2344fae2001-01-15 00:50:52 +0000811 cond = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000812 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000813 bp = self.get_bpbynumber(args[0].strip())
Georg Brandl0079ffc2013-10-14 16:08:15 +0200814 except IndexError:
815 self.error('Breakpoint number expected')
Georg Brandl7410dd12010-07-30 12:01:20 +0000816 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000817 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000818 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000819 bp.cond = cond
820 if not cond:
Georg Brandl0d089622010-07-30 16:00:46 +0000821 self.message('Breakpoint %d is now unconditional.' % bp.number)
Georg Brandl7410dd12010-07-30 12:01:20 +0000822 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000823 self.message('New condition set for breakpoint %d.' % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000824
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100825 complete_condition = _complete_bpnumber
826
Georg Brandl7410dd12010-07-30 12:01:20 +0000827 def do_ignore(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000828 """ignore bpnumber [count]
829 Set the ignore count for the given breakpoint number. If
830 count is omitted, the ignore count is set to 0. A breakpoint
831 becomes active when the ignore count is zero. When non-zero,
832 the count is decremented each time the breakpoint is reached
833 and the breakpoint is not disabled and any associated
834 condition evaluates to true.
835 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000836 args = arg.split()
Thomas Woutersb2137042007-02-01 18:02:27 +0000837 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000838 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000839 except:
840 count = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +0000841 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000842 bp = self.get_bpbynumber(args[0].strip())
Georg Brandl0079ffc2013-10-14 16:08:15 +0200843 except IndexError:
844 self.error('Breakpoint number expected')
Georg Brandl7410dd12010-07-30 12:01:20 +0000845 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000846 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000847 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000848 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000849 if count > 0:
Guido van Rossum08454592002-07-12 13:10:53 +0000850 if count > 1:
Georg Brandl0d089622010-07-30 16:00:46 +0000851 countstr = '%d crossings' % count
Tim Peters2344fae2001-01-15 00:50:52 +0000852 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000853 countstr = '1 crossing'
854 self.message('Will ignore next %s of breakpoint %d.' %
855 (countstr, bp.number))
Tim Peters2344fae2001-01-15 00:50:52 +0000856 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000857 self.message('Will stop next time breakpoint %d is reached.'
858 % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000859
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100860 complete_ignore = _complete_bpnumber
861
Tim Peters2344fae2001-01-15 00:50:52 +0000862 def do_clear(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000863 """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]]
864 With a space separated list of breakpoint numbers, clear
865 those breakpoints. Without argument, clear all breaks (but
866 first ask confirmation). With a filename:lineno argument,
867 clear all breaks at that line in that file.
868 """
Tim Peters2344fae2001-01-15 00:50:52 +0000869 if not arg:
870 try:
Guido van Rossumc5b6ab02007-05-27 09:19:52 +0000871 reply = input('Clear all breaks? ')
Tim Peters2344fae2001-01-15 00:50:52 +0000872 except EOFError:
873 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000874 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000875 if reply in ('y', 'yes'):
Georg Brandl7410dd12010-07-30 12:01:20 +0000876 bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp]
Tim Peters2344fae2001-01-15 00:50:52 +0000877 self.clear_all_breaks()
Georg Brandl7410dd12010-07-30 12:01:20 +0000878 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000879 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000880 return
881 if ':' in arg:
882 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000883 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000884 filename = arg[:i]
885 arg = arg[i+1:]
886 try:
887 lineno = int(arg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000888 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000889 err = "Invalid line number (%s)" % arg
890 else:
Georg Brandl7410dd12010-07-30 12:01:20 +0000891 bplist = self.get_breaks(filename, lineno)
Tim Peters2344fae2001-01-15 00:50:52 +0000892 err = self.clear_break(filename, lineno)
Georg Brandl7410dd12010-07-30 12:01:20 +0000893 if err:
Georg Brandl0d089622010-07-30 16:00:46 +0000894 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000895 else:
896 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000897 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000898 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000899 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000900 for i in numberlist:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000901 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000902 bp = self.get_bpbynumber(i)
903 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000904 self.error(err)
Tim Peters2344fae2001-01-15 00:50:52 +0000905 else:
Senthil Kumaran6f107042010-11-29 11:54:17 +0000906 self.clear_bpbynumber(i)
Georg Brandl0d089622010-07-30 16:00:46 +0000907 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000908 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
909
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100910 complete_clear = _complete_location
911 complete_cl = _complete_location
912
Tim Peters2344fae2001-01-15 00:50:52 +0000913 def do_where(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000914 """w(here)
915 Print a stack trace, with the most recent frame at the bottom.
916 An arrow indicates the "current frame", which determines the
917 context of most commands. 'bt' is an alias for this command.
918 """
Tim Peters2344fae2001-01-15 00:50:52 +0000919 self.print_stack_trace()
920 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000921 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000922
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000923 def _select_frame(self, number):
924 assert 0 <= number < len(self.stack)
925 self.curindex = number
926 self.curframe = self.stack[self.curindex][0]
927 self.curframe_locals = self.curframe.f_locals
928 self.print_stack_entry(self.stack[self.curindex])
929 self.lineno = None
930
Tim Peters2344fae2001-01-15 00:50:52 +0000931 def do_up(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000932 """u(p) [count]
933 Move the current frame count (default one) levels up in the
934 stack trace (to an older frame).
935 """
Tim Peters2344fae2001-01-15 00:50:52 +0000936 if self.curindex == 0:
Georg Brandl0d089622010-07-30 16:00:46 +0000937 self.error('Oldest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000938 return
939 try:
940 count = int(arg or 1)
941 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000942 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000943 return
944 if count < 0:
945 newframe = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000946 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000947 newframe = max(0, self.curindex - count)
948 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000949 do_u = do_up
950
951 def do_down(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000952 """d(own) [count]
953 Move the current frame count (default one) levels down in the
954 stack trace (to a newer frame).
955 """
Tim Peters2344fae2001-01-15 00:50:52 +0000956 if self.curindex + 1 == len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +0000957 self.error('Newest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000958 return
959 try:
960 count = int(arg or 1)
961 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000962 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000963 return
964 if count < 0:
965 newframe = len(self.stack) - 1
Tim Peters2344fae2001-01-15 00:50:52 +0000966 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000967 newframe = min(len(self.stack) - 1, self.curindex + count)
968 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000969 do_d = do_down
970
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000971 def do_until(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000972 """unt(il) [lineno]
973 Without argument, continue execution until the line with a
974 number greater than the current one is reached. With a line
975 number, continue execution until a line with a number greater
976 or equal to that is reached. In both cases, also stop when
977 the current frame returns.
978 """
Georg Brandl2dfec552010-07-30 08:43:32 +0000979 if arg:
980 try:
981 lineno = int(arg)
982 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000983 self.error('Error in argument: %r' % arg)
Georg Brandl2dfec552010-07-30 08:43:32 +0000984 return
985 if lineno <= self.curframe.f_lineno:
Georg Brandl0d089622010-07-30 16:00:46 +0000986 self.error('"until" line number is smaller than current '
987 'line number')
Georg Brandl2dfec552010-07-30 08:43:32 +0000988 return
989 else:
990 lineno = None
991 self.set_until(self.curframe, lineno)
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000992 return 1
993 do_unt = do_until
994
Tim Peters2344fae2001-01-15 00:50:52 +0000995 def do_step(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000996 """s(tep)
997 Execute the current line, stop at the first possible occasion
998 (either in a function that is called or in the current
999 function).
1000 """
Tim Peters2344fae2001-01-15 00:50:52 +00001001 self.set_step()
1002 return 1
1003 do_s = do_step
1004
1005 def do_next(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001006 """n(ext)
1007 Continue execution until the next line in the current function
1008 is reached or it returns.
1009 """
Tim Peters2344fae2001-01-15 00:50:52 +00001010 self.set_next(self.curframe)
1011 return 1
1012 do_n = do_next
1013
Guido van Rossumd8faa362007-04-27 19:54:29 +00001014 def do_run(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001015 """run [args...]
1016 Restart the debugged python program. If a string is supplied
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001017 it is split with "shlex", and the result is used as the new
Georg Brandl0d089622010-07-30 16:00:46 +00001018 sys.argv. History, breakpoints, actions and debugger options
1019 are preserved. "restart" is an alias for "run".
1020 """
Guido van Rossumd8faa362007-04-27 19:54:29 +00001021 if arg:
1022 import shlex
1023 argv0 = sys.argv[0:1]
1024 sys.argv = shlex.split(arg)
1025 sys.argv[:0] = argv0
Georg Brandl0d089622010-07-30 16:00:46 +00001026 # this is caught in the main debugger loop
Guido van Rossumd8faa362007-04-27 19:54:29 +00001027 raise Restart
1028
1029 do_restart = do_run
1030
Tim Peters2344fae2001-01-15 00:50:52 +00001031 def do_return(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001032 """r(eturn)
1033 Continue execution until the current function returns.
1034 """
Tim Peters2344fae2001-01-15 00:50:52 +00001035 self.set_return(self.curframe)
1036 return 1
1037 do_r = do_return
1038
1039 def do_continue(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001040 """c(ont(inue))
1041 Continue execution, only stop when a breakpoint is encountered.
1042 """
Georg Brandl44f2b642010-12-04 16:00:47 +00001043 if not self.nosigint:
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001044 try:
Xavier de Gaye10e54ae2016-10-12 20:13:24 +02001045 Pdb._previous_sigint_handler = \
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001046 signal.signal(signal.SIGINT, self.sigint_handler)
1047 except ValueError:
1048 # ValueError happens when do_continue() is invoked from
1049 # a non-main thread in which case we just continue without
1050 # SIGINT set. Would printing a message here (once) make
1051 # sense?
1052 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001053 self.set_continue()
1054 return 1
1055 do_c = do_cont = do_continue
1056
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001057 def do_jump(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001058 """j(ump) lineno
1059 Set the next line that will be executed. Only available in
1060 the bottom-most frame. This lets you jump back and execute
1061 code again, or jump forward to skip code that you don't want
1062 to run.
1063
1064 It should be noted that not all jumps are allowed -- for
1065 instance it is not possible to jump into the middle of a
1066 for loop or out of a finally clause.
1067 """
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001068 if self.curindex + 1 != len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +00001069 self.error('You can only jump within the bottom frame')
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001070 return
1071 try:
1072 arg = int(arg)
1073 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +00001074 self.error("The 'jump' command requires a line number")
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001075 else:
1076 try:
1077 # Do the jump, fix up our copy of the stack, and display the
1078 # new position
1079 self.curframe.f_lineno = arg
1080 self.stack[self.curindex] = self.stack[self.curindex][0], arg
1081 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumb940e112007-01-10 16:19:56 +00001082 except ValueError as e:
Georg Brandl0d089622010-07-30 16:00:46 +00001083 self.error('Jump failed: %s' % e)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001084 do_j = do_jump
1085
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001086 def do_debug(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001087 """debug code
1088 Enter a recursive debugger that steps through the code
1089 argument (which is an arbitrary expression or statement to be
1090 executed in the current environment).
1091 """
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001092 sys.settrace(None)
1093 globals = self.curframe.f_globals
Benjamin Petersond23f8222009-04-05 19:13:16 +00001094 locals = self.curframe_locals
Guido van Rossum7736b5b2008-01-15 21:44:53 +00001095 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +00001096 p.prompt = "(%s) " % self.prompt.strip()
Georg Brandl0d089622010-07-30 16:00:46 +00001097 self.message("ENTERING RECURSIVE DEBUGGER")
Daniel Hahler3e936432019-03-12 04:29:04 +01001098 try:
1099 sys.call_tracing(p.run, (arg, globals, locals))
1100 except Exception:
1101 exc_info = sys.exc_info()[:2]
1102 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Georg Brandl0d089622010-07-30 16:00:46 +00001103 self.message("LEAVING RECURSIVE DEBUGGER")
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001104 sys.settrace(self.trace_dispatch)
1105 self.lastcmd = p.lastcmd
1106
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001107 complete_debug = _complete_expression
1108
Tim Peters2344fae2001-01-15 00:50:52 +00001109 def do_quit(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001110 """q(uit)\nexit
1111 Quit from the debugger. The program being executed is aborted.
1112 """
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001113 self._user_requested_quit = True
Tim Peters2344fae2001-01-15 00:50:52 +00001114 self.set_quit()
1115 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001116
Tim Peters2344fae2001-01-15 00:50:52 +00001117 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +00001118 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +00001119
Guido van Rossumeef26072003-01-13 21:13:55 +00001120 def do_EOF(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001121 """EOF
1122 Handles the receipt of EOF as a command.
1123 """
1124 self.message('')
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001125 self._user_requested_quit = True
Guido van Rossumeef26072003-01-13 21:13:55 +00001126 self.set_quit()
1127 return 1
1128
Tim Peters2344fae2001-01-15 00:50:52 +00001129 def do_args(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001130 """a(rgs)
1131 Print the argument list of the current function.
1132 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001133 co = self.curframe.f_code
1134 dict = self.curframe_locals
Pablo Galindocd74e662019-06-01 18:08:04 +01001135 n = co.co_argcount + co.co_kwonlyargcount
RĂ©mi Lapeyrebf457c72019-05-21 00:17:30 +02001136 if co.co_flags & inspect.CO_VARARGS: n = n+1
1137 if co.co_flags & inspect.CO_VARKEYWORDS: n = n+1
Tim Peters2344fae2001-01-15 00:50:52 +00001138 for i in range(n):
1139 name = co.co_varnames[i]
Georg Brandl0d089622010-07-30 16:00:46 +00001140 if name in dict:
1141 self.message('%s = %r' % (name, dict[name]))
1142 else:
1143 self.message('%s = *** undefined ***' % (name,))
Tim Peters2344fae2001-01-15 00:50:52 +00001144 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +00001145
Tim Peters2344fae2001-01-15 00:50:52 +00001146 def do_retval(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001147 """retval
1148 Print the return value for the last return of a function.
1149 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001150 if '__return__' in self.curframe_locals:
Georg Brandl0d089622010-07-30 16:00:46 +00001151 self.message(repr(self.curframe_locals['__return__']))
Tim Peters2344fae2001-01-15 00:50:52 +00001152 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001153 self.error('Not yet returned!')
Tim Peters2344fae2001-01-15 00:50:52 +00001154 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +00001155
Barry Warsaw210bd202002-11-05 22:40:20 +00001156 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +00001157 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +00001158 return eval(arg, self.curframe.f_globals, self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +00001159 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001160 exc_info = sys.exc_info()[:2]
1161 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Barry Warsaw210bd202002-11-05 22:40:20 +00001162 raise
Guido van Rossum2424f851998-09-11 22:50:09 +00001163
Georg Brandlcbc79c72010-12-04 16:21:42 +00001164 def _getval_except(self, arg, frame=None):
1165 try:
1166 if frame is None:
1167 return eval(arg, self.curframe.f_globals, self.curframe_locals)
1168 else:
1169 return eval(arg, frame.f_globals, frame.f_locals)
1170 except:
1171 exc_info = sys.exc_info()[:2]
1172 err = traceback.format_exception_only(*exc_info)[-1].strip()
1173 return _rstr('** raised %s **' % err)
1174
Barry Warsaw210bd202002-11-05 22:40:20 +00001175 def do_p(self, arg):
R David Murray78d692f2013-10-10 17:23:26 -04001176 """p expression
Georg Brandl0d089622010-07-30 16:00:46 +00001177 Print the value of the expression.
1178 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001179 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001180 self.message(repr(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001181 except:
1182 pass
1183
1184 def do_pp(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001185 """pp expression
1186 Pretty-print the value of the expression.
1187 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001188 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001189 self.message(pprint.pformat(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001190 except:
1191 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001192
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001193 complete_print = _complete_expression
1194 complete_p = _complete_expression
1195 complete_pp = _complete_expression
1196
Tim Peters2344fae2001-01-15 00:50:52 +00001197 def do_list(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001198 """l(ist) [first [,last] | .]
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001199
1200 List source code for the current file. Without arguments,
1201 list 11 lines around the current line or continue the previous
1202 listing. With . as argument, list 11 lines around the current
1203 line. With one argument, list 11 lines starting at that line.
1204 With two arguments, list the given range; if the second
1205 argument is less than the first, it is a count.
1206
1207 The current line in the current frame is indicated by "->".
1208 If an exception is being debugged, the line where the
1209 exception was originally raised or propagated is indicated by
1210 ">>", if it differs from the current line.
Georg Brandl0d089622010-07-30 16:00:46 +00001211 """
Tim Peters2344fae2001-01-15 00:50:52 +00001212 self.lastcmd = 'list'
1213 last = None
Georg Brandla91a94b2010-07-30 07:14:01 +00001214 if arg and arg != '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001215 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001216 if ',' in arg:
1217 first, last = arg.split(',')
1218 first = int(first.strip())
1219 last = int(last.strip())
Tim Peters2344fae2001-01-15 00:50:52 +00001220 if last < first:
Georg Brandl0d089622010-07-30 16:00:46 +00001221 # assume it's a count
Tim Peters2344fae2001-01-15 00:50:52 +00001222 last = first + last
1223 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001224 first = int(arg.strip())
1225 first = max(1, first - 5)
1226 except ValueError:
1227 self.error('Error in argument: %r' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001228 return
Georg Brandla91a94b2010-07-30 07:14:01 +00001229 elif self.lineno is None or arg == '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001230 first = max(1, self.curframe.f_lineno - 5)
1231 else:
1232 first = self.lineno + 1
1233 if last is None:
1234 last = first + 10
1235 filename = self.curframe.f_code.co_filename
1236 breaklist = self.get_file_breaks(filename)
1237 try:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001238 lines = linecache.getlines(filename, self.curframe.f_globals)
1239 self._print_lines(lines[first-1:last], first, breaklist,
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001240 self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001241 self.lineno = min(last, len(lines))
1242 if len(lines) < last:
1243 self.message('[EOF]')
Tim Peters2344fae2001-01-15 00:50:52 +00001244 except KeyboardInterrupt:
1245 pass
1246 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +00001247
Georg Brandle59ca2a2010-07-30 17:04:28 +00001248 def do_longlist(self, arg):
1249 """longlist | ll
1250 List the whole source code for the current function or frame.
1251 """
1252 filename = self.curframe.f_code.co_filename
1253 breaklist = self.get_file_breaks(filename)
1254 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001255 lines, lineno = getsourcelines(self.curframe)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001256 except OSError as err:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001257 self.error(err)
1258 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001259 self._print_lines(lines, lineno, breaklist, self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001260 do_ll = do_longlist
1261
1262 def do_source(self, arg):
1263 """source expression
1264 Try to get source code for the given object and display it.
1265 """
1266 try:
1267 obj = self._getval(arg)
1268 except:
1269 return
1270 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001271 lines, lineno = getsourcelines(obj)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001272 except (OSError, TypeError) as err:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001273 self.error(err)
1274 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001275 self._print_lines(lines, lineno)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001276
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001277 complete_source = _complete_expression
1278
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001279 def _print_lines(self, lines, start, breaks=(), frame=None):
Georg Brandle59ca2a2010-07-30 17:04:28 +00001280 """Print a range of lines."""
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001281 if frame:
1282 current_lineno = frame.f_lineno
1283 exc_lineno = self.tb_lineno.get(frame, -1)
1284 else:
1285 current_lineno = exc_lineno = -1
Georg Brandle59ca2a2010-07-30 17:04:28 +00001286 for lineno, line in enumerate(lines, start):
1287 s = str(lineno).rjust(3)
1288 if len(s) < 4:
1289 s += ' '
1290 if lineno in breaks:
1291 s += 'B'
1292 else:
1293 s += ' '
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001294 if lineno == current_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001295 s += '->'
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001296 elif lineno == exc_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001297 s += '>>'
1298 self.message(s + '\t' + line.rstrip())
1299
Tim Peters2344fae2001-01-15 00:50:52 +00001300 def do_whatis(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001301 """whatis arg
1302 Print the type of the argument.
1303 """
Tim Peters2344fae2001-01-15 00:50:52 +00001304 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001305 value = self._getval(arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001306 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001307 # _getval() already printed the error
Tim Peters2344fae2001-01-15 00:50:52 +00001308 return
1309 code = None
1310 # Is it a function?
Georg Brandl0d089622010-07-30 16:00:46 +00001311 try:
1312 code = value.__code__
1313 except Exception:
1314 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001315 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001316 self.message('Function %s' % code.co_name)
Tim Peters2344fae2001-01-15 00:50:52 +00001317 return
1318 # Is it an instance method?
Georg Brandl0d089622010-07-30 16:00:46 +00001319 try:
1320 code = value.__func__.__code__
1321 except Exception:
1322 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001323 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001324 self.message('Method %s' % code.co_name)
1325 return
1326 # Is it a class?
1327 if value.__class__ is type:
Serhiy Storchaka521e5862014-07-22 15:00:37 +03001328 self.message('Class %s.%s' % (value.__module__, value.__qualname__))
Tim Peters2344fae2001-01-15 00:50:52 +00001329 return
1330 # None of the above...
Georg Brandl0d089622010-07-30 16:00:46 +00001331 self.message(type(value))
Guido van Rossum8e2ec561993-07-29 09:37:38 +00001332
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001333 complete_whatis = _complete_expression
1334
Georg Brandlcbc79c72010-12-04 16:21:42 +00001335 def do_display(self, arg):
1336 """display [expression]
1337
1338 Display the value of the expression if it changed, each time execution
1339 stops in the current frame.
1340
1341 Without expression, list all display expressions for the current frame.
1342 """
1343 if not arg:
1344 self.message('Currently displaying:')
1345 for item in self.displaying.get(self.curframe, {}).items():
1346 self.message('%s: %r' % item)
1347 else:
1348 val = self._getval_except(arg)
1349 self.displaying.setdefault(self.curframe, {})[arg] = val
1350 self.message('display %s: %r' % (arg, val))
1351
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001352 complete_display = _complete_expression
1353
Georg Brandlcbc79c72010-12-04 16:21:42 +00001354 def do_undisplay(self, arg):
1355 """undisplay [expression]
1356
1357 Do not display the expression any more in the current frame.
1358
1359 Without expression, clear all display expressions for the current frame.
1360 """
1361 if arg:
1362 try:
1363 del self.displaying.get(self.curframe, {})[arg]
1364 except KeyError:
1365 self.error('not displaying %s' % arg)
1366 else:
1367 self.displaying.pop(self.curframe, None)
1368
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001369 def complete_undisplay(self, text, line, begidx, endidx):
1370 return [e for e in self.displaying.get(self.curframe, {})
1371 if e.startswith(text)]
1372
Georg Brandl1acb7462010-12-04 11:20:26 +00001373 def do_interact(self, arg):
1374 """interact
1375
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001376 Start an interactive interpreter whose global namespace
Georg Brandl1acb7462010-12-04 11:20:26 +00001377 contains all the (global and local) names found in the current scope.
1378 """
Serhiy Storchakada084702019-03-27 08:02:28 +02001379 ns = {**self.curframe.f_globals, **self.curframe_locals}
Georg Brandl1acb7462010-12-04 11:20:26 +00001380 code.interact("*interactive*", local=ns)
1381
Tim Peters2344fae2001-01-15 00:50:52 +00001382 def do_alias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001383 """alias [name [command [parameter parameter ...] ]]
1384 Create an alias called 'name' that executes 'command'. The
1385 command must *not* be enclosed in quotes. Replaceable
1386 parameters can be indicated by %1, %2, and so on, while %* is
1387 replaced by all the parameters. If no command is given, the
1388 current alias for name is shown. If no name is given, all
1389 aliases are listed.
1390
1391 Aliases may be nested and can contain anything that can be
1392 legally typed at the pdb prompt. Note! You *can* override
1393 internal pdb commands with aliases! Those internal commands
1394 are then hidden until the alias is removed. Aliasing is
1395 recursively applied to the first word of the command line; all
1396 other words in the line are left alone.
1397
1398 As an example, here are two useful aliases (especially when
1399 placed in the .pdbrc file):
1400
1401 # Print instance variables (usage "pi classInst")
R David Murray78d692f2013-10-10 17:23:26 -04001402 alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])
Georg Brandl0d089622010-07-30 16:00:46 +00001403 # Print instance variables in self
1404 alias ps pi self
1405 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001406 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001407 if len(args) == 0:
Benjamin Petersonbe74a372009-09-11 21:17:13 +00001408 keys = sorted(self.aliases.keys())
Tim Peters2344fae2001-01-15 00:50:52 +00001409 for alias in keys:
Georg Brandl0d089622010-07-30 16:00:46 +00001410 self.message("%s = %s" % (alias, self.aliases[alias]))
Tim Peters2344fae2001-01-15 00:50:52 +00001411 return
Guido van Rossum08454592002-07-12 13:10:53 +00001412 if args[0] in self.aliases and len(args) == 1:
Georg Brandl0d089622010-07-30 16:00:46 +00001413 self.message("%s = %s" % (args[0], self.aliases[args[0]]))
Tim Peters2344fae2001-01-15 00:50:52 +00001414 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001415 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +00001416
Tim Peters2344fae2001-01-15 00:50:52 +00001417 def do_unalias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001418 """unalias name
1419 Delete the specified alias.
1420 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001421 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001422 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +00001423 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +00001424 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +00001425
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001426 def complete_unalias(self, text, line, begidx, endidx):
1427 return [a for a in self.aliases if a.startswith(text)]
1428
Georg Brandl0d089622010-07-30 16:00:46 +00001429 # List of all the commands making the program resume execution.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001430 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
1431 'do_quit', 'do_jump']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001432
Tim Peters2344fae2001-01-15 00:50:52 +00001433 # Print a traceback starting at the top stack frame.
1434 # The most recently entered frame is printed last;
1435 # this is different from dbx and gdb, but consistent with
1436 # the Python interpreter's stack trace.
1437 # It is also consistent with the up/down commands (which are
1438 # compatible with dbx and gdb: up moves towards 'main()'
1439 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +00001440
Tim Peters2344fae2001-01-15 00:50:52 +00001441 def print_stack_trace(self):
1442 try:
1443 for frame_lineno in self.stack:
1444 self.print_stack_entry(frame_lineno)
1445 except KeyboardInterrupt:
1446 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001447
Tim Peters2344fae2001-01-15 00:50:52 +00001448 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
1449 frame, lineno = frame_lineno
1450 if frame is self.curframe:
Georg Brandl0d089622010-07-30 16:00:46 +00001451 prefix = '> '
Tim Peters2344fae2001-01-15 00:50:52 +00001452 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001453 prefix = ' '
1454 self.message(prefix +
1455 self.format_stack_entry(frame_lineno, prompt_prefix))
Guido van Rossum2424f851998-09-11 22:50:09 +00001456
Georg Brandl0d089622010-07-30 16:00:46 +00001457 # Provide help
Guido van Rossum921c8241992-01-10 14:54:42 +00001458
Georg Brandl0d089622010-07-30 16:00:46 +00001459 def do_help(self, arg):
1460 """h(elp)
1461 Without argument, print the list of available commands.
1462 With a command name as argument, print help about that command.
1463 "help pdb" shows the full pdb documentation.
1464 "help exec" gives help on the ! command.
1465 """
1466 if not arg:
1467 return cmd.Cmd.do_help(self, arg)
1468 try:
1469 try:
1470 topic = getattr(self, 'help_' + arg)
1471 return topic()
1472 except AttributeError:
1473 command = getattr(self, 'do_' + arg)
1474 except AttributeError:
1475 self.error('No help for %r' % arg)
1476 else:
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001477 if sys.flags.optimize >= 2:
1478 self.error('No help for %r; please do not run Python with -OO '
1479 'if you need command help' % arg)
1480 return
Georg Brandl0d089622010-07-30 16:00:46 +00001481 self.message(command.__doc__.rstrip())
Guido van Rossum921c8241992-01-10 14:54:42 +00001482
Georg Brandl0d089622010-07-30 16:00:46 +00001483 do_h = do_help
Barry Warsaw210bd202002-11-05 22:40:20 +00001484
Tim Peters2344fae2001-01-15 00:50:52 +00001485 def help_exec(self):
Georg Brandl0d089622010-07-30 16:00:46 +00001486 """(!) statement
1487 Execute the (one-line) statement in the context of the current
1488 stack frame. The exclamation point can be omitted unless the
1489 first word of the statement resembles a debugger command. To
1490 assign to a global variable you must always prefix the command
1491 with a 'global' command, e.g.:
1492 (Pdb) global list_options; list_options = ['-l']
1493 (Pdb)
1494 """
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001495 self.message((self.help_exec.__doc__ or '').strip())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001496
Tim Peters2344fae2001-01-15 00:50:52 +00001497 def help_pdb(self):
1498 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001499
Georg Brandl0d089622010-07-30 16:00:46 +00001500 # other helper functions
1501
Tim Peters2344fae2001-01-15 00:50:52 +00001502 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001503 """Helper function for break/clear parsing -- may be overridden.
1504
1505 lookupmodule() translates (possibly incomplete) file or module name
1506 into an absolute file name.
1507 """
1508 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001509 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001510 f = os.path.join(sys.path[0], filename)
1511 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1512 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001513 root, ext = os.path.splitext(filename)
1514 if ext == '':
1515 filename = filename + '.py'
1516 if os.path.isabs(filename):
1517 return filename
1518 for dirname in sys.path:
1519 while os.path.islink(dirname):
1520 dirname = os.readlink(dirname)
1521 fullname = os.path.join(dirname, filename)
1522 if os.path.exists(fullname):
1523 return fullname
1524 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001525
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001526 def _runmodule(self, module_name):
1527 self._wait_for_mainpyfile = True
1528 self._user_requested_quit = False
1529 import runpy
1530 mod_name, mod_spec, code = runpy._get_module_details(module_name)
1531 self.mainpyfile = self.canonic(code.co_filename)
1532 import __main__
1533 __main__.__dict__.clear()
1534 __main__.__dict__.update({
1535 "__name__": "__main__",
1536 "__file__": self.mainpyfile,
Mario Corchero38bfa842018-02-03 06:40:11 +00001537 "__package__": mod_spec.parent,
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001538 "__loader__": mod_spec.loader,
1539 "__spec__": mod_spec,
1540 "__builtins__": __builtins__,
1541 })
1542 self.run(code)
1543
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001544 def _runscript(self, filename):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001545 # The script has to run in __main__ namespace (or imports from
1546 # __main__ will break).
1547 #
1548 # So we clear up the __main__ and set several special variables
1549 # (this gets rid of pdb's globals and cleans old variables on restarts).
1550 import __main__
1551 __main__.__dict__.clear()
1552 __main__.__dict__.update({"__name__" : "__main__",
1553 "__file__" : filename,
1554 "__builtins__": __builtins__,
1555 })
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001556
1557 # When bdb sets tracing, a number of call and line events happens
1558 # BEFORE debugger even reaches user's code (and the exact sequence of
1559 # events depends on python version). So we take special measures to
1560 # avoid stopping before we reach the main script (see user_line and
1561 # user_call for details).
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001562 self._wait_for_mainpyfile = True
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001563 self.mainpyfile = self.canonic(filename)
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001564 self._user_requested_quit = False
Georg Brandld07ac642009-08-13 07:50:57 +00001565 with open(filename, "rb") as fp:
1566 statement = "exec(compile(%r, %r, 'exec'))" % \
1567 (fp.read(), self.mainpyfile)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001568 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001569
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001570# Collect all command help into docstring, if not run with -OO
Georg Brandl0d089622010-07-30 16:00:46 +00001571
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001572if __doc__ is not None:
1573 # unfortunately we can't guess this order from the class definition
1574 _help_order = [
1575 'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable',
1576 'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until',
1577 'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist',
R David Murray78d692f2013-10-10 17:23:26 -04001578 'args', 'p', 'pp', 'whatis', 'source', 'display', 'undisplay',
Georg Brandlcbc79c72010-12-04 16:21:42 +00001579 'interact', 'alias', 'unalias', 'debug', 'quit',
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001580 ]
Georg Brandl0d089622010-07-30 16:00:46 +00001581
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001582 for _command in _help_order:
1583 __doc__ += getattr(Pdb, 'do_' + _command).__doc__.strip() + '\n\n'
1584 __doc__ += Pdb.help_exec.__doc__
Georg Brandl0d089622010-07-30 16:00:46 +00001585
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001586 del _help_order, _command
1587
Georg Brandl0d089622010-07-30 16:00:46 +00001588
Guido van Rossum35771131992-09-08 11:59:04 +00001589# Simplified interface
1590
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001591def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001592 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001593
1594def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001595 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001596
1597def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001598 # B/W compatibility
1599 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001600
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001601def runcall(*args, **kwds):
1602 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001603
Barry Warsaw35425d62017-09-22 12:29:42 -04001604def set_trace(*, header=None):
1605 pdb = Pdb()
1606 if header is not None:
1607 pdb.message(header)
1608 pdb.set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001609
1610# Post-Mortem interface
1611
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001612def post_mortem(t=None):
1613 # handling the default
1614 if t is None:
1615 # sys.exc_info() returns (type, value, traceback) if an exception is
1616 # being handled, otherwise it returns None
1617 t = sys.exc_info()[2]
Georg Brandl0d089622010-07-30 16:00:46 +00001618 if t is None:
1619 raise ValueError("A valid traceback must be passed if no "
1620 "exception is being handled")
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001621
Tim Peters2344fae2001-01-15 00:50:52 +00001622 p = Pdb()
1623 p.reset()
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001624 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001625
1626def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001627 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001628
1629
1630# Main program for testing
1631
Guido van Rossum23efba41992-01-27 16:58:47 +00001632TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001633
Guido van Rossum921c8241992-01-10 14:54:42 +00001634def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001635 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001636
1637# print help
1638def help():
Georg Brandl02053ee2010-07-18 10:11:03 +00001639 import pydoc
1640 pydoc.pager(__doc__)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001641
Georg Brandle0230912010-07-30 08:29:39 +00001642_usage = """\
Mario Corcherofcf8b4c2018-01-28 04:58:47 +00001643usage: pdb.py [-c command] ... [-m module | pyfile] [arg] ...
Georg Brandle0230912010-07-30 08:29:39 +00001644
Mario Corcherofcf8b4c2018-01-28 04:58:47 +00001645Debug the Python program given by pyfile. Alternatively,
1646an executable module or package to debug can be specified using
1647the -m switch.
Georg Brandle0230912010-07-30 08:29:39 +00001648
1649Initial commands are read from .pdbrc files in your home directory
1650and in the current directory, if they exist. Commands supplied with
1651-c are executed after commands from .pdbrc files.
1652
1653To let the script run until an exception occurs, use "-c continue".
Georg Brandl2dfec552010-07-30 08:43:32 +00001654To let the script run up to a given line X in the debugged file, use
1655"-c 'until X'"."""
Georg Brandle0230912010-07-30 08:29:39 +00001656
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001657def main():
Georg Brandle0230912010-07-30 08:29:39 +00001658 import getopt
1659
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001660 opts, args = getopt.getopt(sys.argv[1:], 'mhc:', ['--help', '--command='])
Georg Brandle0230912010-07-30 08:29:39 +00001661
1662 if not args:
1663 print(_usage)
Tim Peters2344fae2001-01-15 00:50:52 +00001664 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001665
Georg Brandle0230912010-07-30 08:29:39 +00001666 commands = []
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001667 run_as_module = False
Georg Brandle0230912010-07-30 08:29:39 +00001668 for opt, optarg in opts:
1669 if opt in ['-h', '--help']:
1670 print(_usage)
1671 sys.exit()
1672 elif opt in ['-c', '--command']:
1673 commands.append(optarg)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001674 elif opt in ['-m']:
1675 run_as_module = True
Georg Brandle0230912010-07-30 08:29:39 +00001676
1677 mainpyfile = args[0] # Get script filename
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001678 if not run_as_module and not os.path.exists(mainpyfile):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001679 print('Error:', mainpyfile, 'does not exist')
Tim Peters2344fae2001-01-15 00:50:52 +00001680 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001681
Georg Brandle0230912010-07-30 08:29:39 +00001682 sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001683
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001684 # Replace pdb's dir with script's dir in front of module search path.
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001685 if not run_as_module:
1686 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001687
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001688 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1689 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl3078df02009-05-05 09:11:31 +00001690 # changed by the user from the command line. There is a "restart" command
1691 # which allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001692 pdb = Pdb()
Georg Brandle0230912010-07-30 08:29:39 +00001693 pdb.rcLines.extend(commands)
Georg Brandl1e30bd32010-07-30 07:21:26 +00001694 while True:
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001695 try:
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001696 if run_as_module:
1697 pdb._runmodule(mainpyfile)
1698 else:
1699 pdb._runscript(mainpyfile)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001700 if pdb._user_requested_quit:
1701 break
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001702 print("The program finished and will be restarted")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001703 except Restart:
1704 print("Restarting", mainpyfile, "with arguments:")
Georg Brandle0230912010-07-30 08:29:39 +00001705 print("\t" + " ".join(args))
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001706 except SystemExit:
1707 # In most cases SystemExit does not warrant a post-mortem session.
Georg Brandle0230912010-07-30 08:29:39 +00001708 print("The program exited via sys.exit(). Exit status:", end=' ')
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001709 print(sys.exc_info()[1])
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001710 except SyntaxError:
1711 traceback.print_exc()
1712 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001713 except:
1714 traceback.print_exc()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001715 print("Uncaught exception. Entering post mortem debugging")
1716 print("Running 'cont' or 'step' will restart the program")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001717 t = sys.exc_info()[2]
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001718 pdb.interaction(None, t)
Georg Brandl3078df02009-05-05 09:11:31 +00001719 print("Post mortem debugger finished. The " + mainpyfile +
1720 " will be restarted")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001721
1722
1723# When invoked as main program, invoke the debugger on a script
Guido van Rossumd8faa362007-04-27 19:54:29 +00001724if __name__ == '__main__':
1725 import pdb
1726 pdb.main()