blob: 8639204891cb01e11134bc7f9171ab079b3f6e0d [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)
Miss Islington (bot)8763d432019-06-24 09:09:47 -0700144 sys.audit("pdb.Pdb")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000145 if stdout:
146 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000147 self.prompt = '(Pdb) '
148 self.aliases = {}
Georg Brandlcbc79c72010-12-04 16:21:42 +0000149 self.displaying = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000150 self.mainpyfile = ''
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000151 self._wait_for_mainpyfile = False
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000152 self.tb_lineno = {}
Tim Peters2344fae2001-01-15 00:50:52 +0000153 # Try to load readline if it exists
154 try:
155 import readline
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100156 # remove some common file name delimiters
157 readline.set_completer_delims(' \t\n`@#$%^&*()=+[{]}\\|;:\'",<>?')
Brett Cannoncd171c82013-07-04 17:43:24 -0400158 except ImportError:
Tim Peters2344fae2001-01-15 00:50:52 +0000159 pass
Georg Brandl44f2b642010-12-04 16:00:47 +0000160 self.allow_kbdint = False
161 self.nosigint = nosigint
Guido van Rossum2424f851998-09-11 22:50:09 +0000162
Miss Islington (bot)79af3bd2019-08-02 15:42:50 -0700163 # Read ~/.pdbrc and ./.pdbrc
Tim Peters2344fae2001-01-15 00:50:52 +0000164 self.rcLines = []
Ɓukasz Langa2eb6eca2016-09-09 22:21:17 -0700165 if readrc:
Miss Islington (bot)79af3bd2019-08-02 15:42:50 -0700166 try:
167 with open(os.path.expanduser('~/.pdbrc')) as rcFile:
168 self.rcLines.extend(rcFile)
169 except OSError:
170 pass
Tim Peters2344fae2001-01-15 00:50:52 +0000171 try:
Ɓukasz Langa2eb6eca2016-09-09 22:21:17 -0700172 with open(".pdbrc") as rcFile:
Florent Xicluna7dde7922010-09-03 19:52:03 +0000173 self.rcLines.extend(rcFile)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200174 except OSError:
Tim Peters2344fae2001-01-15 00:50:52 +0000175 pass
Guido van Rossum23efba41992-01-27 16:58:47 +0000176
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000177 self.commands = {} # associates a command list to breakpoint numbers
Benjamin Petersond23f8222009-04-05 19:13:16 +0000178 self.commands_doprompt = {} # for each bp num, tells if the prompt
179 # must be disp. after execing the cmd list
180 self.commands_silent = {} # for each bp num, tells if the stack trace
181 # must be disp. after execing the cmd list
182 self.commands_defining = False # True while in the process of defining
183 # a command list
184 self.commands_bnum = None # The breakpoint number for which we are
185 # defining a list
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000186
Georg Brandl44f2b642010-12-04 16:00:47 +0000187 def sigint_handler(self, signum, frame):
188 if self.allow_kbdint:
189 raise KeyboardInterrupt
190 self.message("\nProgram interrupted. (Use 'cont' to resume).")
191 self.set_step()
192 self.set_trace(frame)
Georg Brandl44f2b642010-12-04 16:00:47 +0000193
Tim Peters2344fae2001-01-15 00:50:52 +0000194 def reset(self):
195 bdb.Bdb.reset(self)
196 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000197
Tim Peters2344fae2001-01-15 00:50:52 +0000198 def forget(self):
199 self.lineno = None
200 self.stack = []
201 self.curindex = 0
202 self.curframe = None
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000203 self.tb_lineno.clear()
Guido van Rossum2424f851998-09-11 22:50:09 +0000204
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000205 def setup(self, f, tb):
Tim Peters2344fae2001-01-15 00:50:52 +0000206 self.forget()
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000207 self.stack, self.curindex = self.get_stack(f, tb)
208 while tb:
209 # when setting up post-mortem debugging with a traceback, save all
210 # the original line numbers to be displayed along the current line
211 # numbers (which can be different, e.g. due to finally clauses)
212 lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti)
213 self.tb_lineno[tb.tb_frame] = lineno
214 tb = tb.tb_next
Tim Peters2344fae2001-01-15 00:50:52 +0000215 self.curframe = self.stack[self.curindex][0]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000216 # The f_locals dictionary is updated from the actual frame
217 # locals whenever the .f_locals accessor is called, so we
218 # cache it here to ensure that modifications are not overwritten.
219 self.curframe_locals = self.curframe.f_locals
Georg Brandle0230912010-07-30 08:29:39 +0000220 return self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000221
Tim Peters2344fae2001-01-15 00:50:52 +0000222 # Can be executed earlier than 'setup' if desired
223 def execRcLines(self):
Georg Brandle0230912010-07-30 08:29:39 +0000224 if not self.rcLines:
225 return
226 # local copy because of recursion
227 rcLines = self.rcLines
228 rcLines.reverse()
229 # execute every line only once
230 self.rcLines = []
231 while rcLines:
232 line = rcLines.pop().strip()
233 if line and line[0] != '#':
234 if self.onecmd(line):
235 # if onecmd returns True, the command wants to exit
236 # from the interaction, save leftover rc lines
237 # to execute before next interaction
238 self.rcLines += reversed(rcLines)
239 return True
Guido van Rossum2424f851998-09-11 22:50:09 +0000240
Tim Peters280488b2002-08-23 18:19:30 +0000241 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000242
243 def user_call(self, frame, argument_list):
244 """This method is called when there is the remote possibility
245 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000246 if self._wait_for_mainpyfile:
247 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000248 if self.stop_here(frame):
Georg Brandl0d089622010-07-30 16:00:46 +0000249 self.message('--Call--')
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000250 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000251
Tim Peters2344fae2001-01-15 00:50:52 +0000252 def user_line(self, frame):
253 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000254 if self._wait_for_mainpyfile:
255 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000256 or frame.f_lineno <= 0):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000257 return
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000258 self._wait_for_mainpyfile = False
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000259 if self.bp_commands(frame):
260 self.interaction(frame, None)
261
Georg Brandle0230912010-07-30 08:29:39 +0000262 def bp_commands(self, frame):
Georg Brandl3078df02009-05-05 09:11:31 +0000263 """Call every command that was set for the current active breakpoint
264 (if there is one).
265
266 Returns True if the normal interaction function must be called,
267 False otherwise."""
268 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
269 if getattr(self, "currentbp", False) and \
270 self.currentbp in self.commands:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000271 currentbp = self.currentbp
272 self.currentbp = 0
273 lastcmd_back = self.lastcmd
274 self.setup(frame, None)
275 for line in self.commands[currentbp]:
276 self.onecmd(line)
277 self.lastcmd = lastcmd_back
278 if not self.commands_silent[currentbp]:
279 self.print_stack_entry(self.stack[self.curindex])
280 if self.commands_doprompt[currentbp]:
Georg Brandl44f2b642010-12-04 16:00:47 +0000281 self._cmdloop()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000282 self.forget()
283 return
284 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000285
Tim Peters2344fae2001-01-15 00:50:52 +0000286 def user_return(self, frame, return_value):
287 """This function is called when a return trap is set here."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000288 if self._wait_for_mainpyfile:
289 return
Tim Peters2344fae2001-01-15 00:50:52 +0000290 frame.f_locals['__return__'] = return_value
Georg Brandl0d089622010-07-30 16:00:46 +0000291 self.message('--Return--')
Tim Peters2344fae2001-01-15 00:50:52 +0000292 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000293
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000294 def user_exception(self, frame, exc_info):
Tim Peters2344fae2001-01-15 00:50:52 +0000295 """This function is called if an exception occurs,
296 but only if we are to stop at or just below this level."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000297 if self._wait_for_mainpyfile:
298 return
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000299 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000300 frame.f_locals['__exception__'] = exc_type, exc_value
Guido van Rossum8820c232013-11-21 11:30:06 -0800301
302 # An 'Internal StopIteration' exception is an exception debug event
303 # issued by the interpreter when handling a subgenerator run with
Martin Panter46f50722016-05-26 05:35:26 +0000304 # 'yield from' or a generator controlled by a for loop. No exception has
Berker Peksagf23530f2014-10-19 18:04:38 +0300305 # actually occurred in this case. The debugger uses this debug event to
Guido van Rossum8820c232013-11-21 11:30:06 -0800306 # stop when the debuggee is returning from such generators.
307 prefix = 'Internal ' if (not exc_traceback
308 and exc_type is StopIteration) else ''
309 self.message('%s%s' % (prefix,
310 traceback.format_exception_only(exc_type, exc_value)[-1].strip()))
Tim Peters2344fae2001-01-15 00:50:52 +0000311 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000312
Tim Peters2344fae2001-01-15 00:50:52 +0000313 # General interaction function
Georg Brandl44f2b642010-12-04 16:00:47 +0000314 def _cmdloop(self):
315 while True:
316 try:
317 # keyboard interrupts allow for an easy way to cancel
318 # the current command, so allow them during interactive input
319 self.allow_kbdint = True
320 self.cmdloop()
321 self.allow_kbdint = False
322 break
323 except KeyboardInterrupt:
324 self.message('--KeyboardInterrupt--')
Tim Peters2344fae2001-01-15 00:50:52 +0000325
Georg Brandlcbc79c72010-12-04 16:21:42 +0000326 # Called before loop, handles display expressions
327 def preloop(self):
328 displaying = self.displaying.get(self.curframe)
329 if displaying:
330 for expr, oldvalue in displaying.items():
331 newvalue = self._getval_except(expr)
332 # check for identity first; this prevents custom __eq__ to
333 # be called at every loop, and also prevents instances whose
334 # fields are changed to be displayed
335 if newvalue is not oldvalue and newvalue != oldvalue:
336 displaying[expr] = newvalue
337 self.message('display %s: %r [old: %r]' %
338 (expr, newvalue, oldvalue))
339
Tim Peters2344fae2001-01-15 00:50:52 +0000340 def interaction(self, frame, traceback):
Xavier de Gaye10e54ae2016-10-12 20:13:24 +0200341 # Restore the previous signal handler at the Pdb prompt.
342 if Pdb._previous_sigint_handler:
Miss Islington (bot)87a5a332019-09-09 04:25:21 -0700343 try:
344 signal.signal(signal.SIGINT, Pdb._previous_sigint_handler)
345 except ValueError: # ValueError: signal only works in main thread
346 pass
347 else:
348 Pdb._previous_sigint_handler = None
Georg Brandle0230912010-07-30 08:29:39 +0000349 if self.setup(frame, traceback):
350 # no interaction desired at this time (happens if .pdbrc contains
351 # a command like "continue")
352 self.forget()
353 return
Tim Peters2344fae2001-01-15 00:50:52 +0000354 self.print_stack_entry(self.stack[self.curindex])
Georg Brandl44f2b642010-12-04 16:00:47 +0000355 self._cmdloop()
Tim Peters2344fae2001-01-15 00:50:52 +0000356 self.forget()
357
Benjamin Petersond23f8222009-04-05 19:13:16 +0000358 def displayhook(self, obj):
359 """Custom displayhook for the exec in default(), which prevents
360 assignment of the _ variable in the builtins.
361 """
Georg Brandl9fa2e022009-09-16 16:40:45 +0000362 # reproduce the behavior of the standard displayhook, not printing None
363 if obj is not None:
Georg Brandl0d089622010-07-30 16:00:46 +0000364 self.message(repr(obj))
Benjamin Petersond23f8222009-04-05 19:13:16 +0000365
Tim Peters2344fae2001-01-15 00:50:52 +0000366 def default(self, line):
367 if line[:1] == '!': line = line[1:]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000368 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000369 globals = self.curframe.f_globals
370 try:
371 code = compile(line + '\n', '<stdin>', 'single')
Christian Heimes679db4a2008-01-18 09:56:22 +0000372 save_stdout = sys.stdout
373 save_stdin = sys.stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000374 save_displayhook = sys.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000375 try:
376 sys.stdin = self.stdin
377 sys.stdout = self.stdout
Benjamin Petersond23f8222009-04-05 19:13:16 +0000378 sys.displayhook = self.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000379 exec(code, globals, locals)
380 finally:
381 sys.stdout = save_stdout
382 sys.stdin = save_stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000383 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000384 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000385 exc_info = sys.exc_info()[:2]
386 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000387
388 def precmd(self, line):
389 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000390 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000391 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000392 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000393 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000394 line = self.aliases[args[0]]
395 ii = 1
396 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000397 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000398 tmpArg)
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000399 ii += 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000400 line = line.replace("%*", ' '.join(args[1:]))
401 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000402 # split into ';;' separated commands
403 # unless it's an alias command
404 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000405 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000406 if marker >= 0:
407 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000408 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000409 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000410 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000411 return line
412
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000413 def onecmd(self, line):
414 """Interpret the argument as though it had been typed in response
415 to the prompt.
416
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000417 Checks whether this line is typed at the normal prompt or in
418 a breakpoint command list definition.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000419 """
420 if not self.commands_defining:
421 return cmd.Cmd.onecmd(self, line)
422 else:
423 return self.handle_command_def(line)
424
Georg Brandlb90ffd82010-07-30 22:20:16 +0000425 def handle_command_def(self, line):
Georg Brandl44f8bf92010-07-30 08:54:49 +0000426 """Handles one command line during command list definition."""
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000427 cmd, arg, line = self.parseline(line)
Georg Brandl44f8bf92010-07-30 08:54:49 +0000428 if not cmd:
429 return
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000430 if cmd == 'silent':
431 self.commands_silent[self.commands_bnum] = True
432 return # continue to handle other cmd def in the cmd list
433 elif cmd == 'end':
434 self.cmdqueue = []
435 return 1 # end of cmd list
436 cmdlist = self.commands[self.commands_bnum]
Georg Brandl44f8bf92010-07-30 08:54:49 +0000437 if arg:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000438 cmdlist.append(cmd+' '+arg)
439 else:
440 cmdlist.append(cmd)
441 # Determine if we must stop
442 try:
443 func = getattr(self, 'do_' + cmd)
444 except AttributeError:
445 func = self.default
Georg Brandl3078df02009-05-05 09:11:31 +0000446 # one of the resuming commands
447 if func.__name__ in self.commands_resuming:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000448 self.commands_doprompt[self.commands_bnum] = False
449 self.cmdqueue = []
450 return 1
451 return
452
Georg Brandl0d089622010-07-30 16:00:46 +0000453 # interface abstraction functions
454
455 def message(self, msg):
456 print(msg, file=self.stdout)
457
458 def error(self, msg):
459 print('***', msg, file=self.stdout)
460
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100461 # Generic completion functions. Individual complete_foo methods can be
462 # assigned below to one of these functions.
463
464 def _complete_location(self, text, line, begidx, endidx):
465 # Complete a file/module/function location for break/tbreak/clear.
466 if line.strip().endswith((':', ',')):
467 # Here comes a line number or a condition which we can't complete.
468 return []
469 # First, try to find matching functions (i.e. expressions).
470 try:
471 ret = self._complete_expression(text, line, begidx, endidx)
472 except Exception:
473 ret = []
474 # Then, try to complete file names as well.
475 globs = glob.glob(text + '*')
476 for fn in globs:
477 if os.path.isdir(fn):
478 ret.append(fn + '/')
479 elif os.path.isfile(fn) and fn.lower().endswith(('.py', '.pyw')):
480 ret.append(fn + ':')
481 return ret
482
483 def _complete_bpnumber(self, text, line, begidx, endidx):
484 # Complete a breakpoint number. (This would be more helpful if we could
485 # display additional info along with the completions, such as file/line
486 # of the breakpoint.)
487 return [str(i) for i, bp in enumerate(bdb.Breakpoint.bpbynumber)
488 if bp is not None and str(i).startswith(text)]
489
490 def _complete_expression(self, text, line, begidx, endidx):
491 # Complete an arbitrary expression.
492 if not self.curframe:
493 return []
494 # Collect globals and locals. It is usually not really sensible to also
495 # complete builtins, and they clutter the namespace quite heavily, so we
496 # leave them out.
Serhiy Storchakada084702019-03-27 08:02:28 +0200497 ns = {**self.curframe.f_globals, **self.curframe_locals}
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100498 if '.' in text:
499 # Walk an attribute chain up to the last part, similar to what
500 # rlcompleter does. This will bail if any of the parts are not
501 # simple attribute access, which is what we want.
502 dotted = text.split('.')
503 try:
504 obj = ns[dotted[0]]
505 for part in dotted[1:-1]:
506 obj = getattr(obj, part)
507 except (KeyError, AttributeError):
508 return []
509 prefix = '.'.join(dotted[:-1]) + '.'
510 return [prefix + n for n in dir(obj) if n.startswith(dotted[-1])]
511 else:
512 # Complete a simple name.
513 return [n for n in ns.keys() if n.startswith(text)]
514
Tim Peters2344fae2001-01-15 00:50:52 +0000515 # Command definitions, called by cmdloop()
516 # The argument is the remaining string on the command line
517 # Return true to exit from the command loop
518
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000519 def do_commands(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000520 """commands [bpnumber]
521 (com) ...
522 (com) end
523 (Pdb)
Georg Brandl3078df02009-05-05 09:11:31 +0000524
Georg Brandl0d089622010-07-30 16:00:46 +0000525 Specify a list of commands for breakpoint number bpnumber.
526 The commands themselves are entered on the following lines.
527 Type a line containing just 'end' to terminate the commands.
528 The commands are executed when the breakpoint is hit.
529
530 To remove all commands from a breakpoint, type commands and
531 follow it immediately with end; that is, give no commands.
532
533 With no bpnumber argument, commands refers to the last
534 breakpoint set.
535
536 You can use breakpoint commands to start your program up
537 again. Simply use the continue command, or step, or any other
538 command that resumes execution.
539
540 Specifying any command resuming execution (currently continue,
541 step, next, return, jump, quit and their abbreviations)
542 terminates the command list (as if that command was
543 immediately followed by end). This is because any time you
544 resume execution (even with a simple next or step), you may
545 encounter another breakpoint -- which could have its own
546 command list, leading to ambiguities about which list to
547 execute.
548
549 If you use the 'silent' command in the command list, the usual
550 message about stopping at a breakpoint is not printed. This
551 may be desirable for breakpoints that are to print a specific
552 message and then continue. If none of the other commands
553 print anything, you will see no sign that the breakpoint was
554 reached.
555 """
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000556 if not arg:
Georg Brandl7410dd12010-07-30 12:01:20 +0000557 bnum = len(bdb.Breakpoint.bpbynumber) - 1
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000558 else:
559 try:
560 bnum = int(arg)
561 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000562 self.error("Usage: commands [bnum]\n ...\n end")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000563 return
564 self.commands_bnum = bnum
Georg Brandlb90ffd82010-07-30 22:20:16 +0000565 # Save old definitions for the case of a keyboard interrupt.
566 if bnum in self.commands:
567 old_command_defs = (self.commands[bnum],
568 self.commands_doprompt[bnum],
569 self.commands_silent[bnum])
570 else:
571 old_command_defs = None
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000572 self.commands[bnum] = []
573 self.commands_doprompt[bnum] = True
574 self.commands_silent[bnum] = False
Georg Brandlb90ffd82010-07-30 22:20:16 +0000575
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000576 prompt_back = self.prompt
577 self.prompt = '(com) '
578 self.commands_defining = True
Georg Brandl44f8bf92010-07-30 08:54:49 +0000579 try:
580 self.cmdloop()
Georg Brandlb90ffd82010-07-30 22:20:16 +0000581 except KeyboardInterrupt:
582 # Restore old definitions.
583 if old_command_defs:
584 self.commands[bnum] = old_command_defs[0]
585 self.commands_doprompt[bnum] = old_command_defs[1]
586 self.commands_silent[bnum] = old_command_defs[2]
587 else:
588 del self.commands[bnum]
589 del self.commands_doprompt[bnum]
590 del self.commands_silent[bnum]
591 self.error('command definition aborted, old commands restored')
Georg Brandl44f8bf92010-07-30 08:54:49 +0000592 finally:
593 self.commands_defining = False
594 self.prompt = prompt_back
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000595
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100596 complete_commands = _complete_bpnumber
597
Tim Peters2344fae2001-01-15 00:50:52 +0000598 def do_break(self, arg, temporary = 0):
Georg Brandl0d089622010-07-30 16:00:46 +0000599 """b(reak) [ ([filename:]lineno | function) [, condition] ]
600 Without argument, list all breaks.
601
602 With a line number argument, set a break at this line in the
603 current file. With a function name, set a break at the first
604 executable line of that function. If a second argument is
605 present, it is a string specifying an expression which must
606 evaluate to true before the breakpoint is honored.
607
608 The line number may be prefixed with a filename and a colon,
609 to specify a breakpoint in another file (probably one that
610 hasn't been loaded yet). The file is searched for on
611 sys.path; the .py suffix may be omitted.
612 """
Tim Peters2344fae2001-01-15 00:50:52 +0000613 if not arg:
614 if self.breaks: # There's at least one
Georg Brandl0d089622010-07-30 16:00:46 +0000615 self.message("Num Type Disp Enb Where")
Tim Peters2344fae2001-01-15 00:50:52 +0000616 for bp in bdb.Breakpoint.bpbynumber:
617 if bp:
Georg Brandl0d089622010-07-30 16:00:46 +0000618 self.message(bp.bpformat())
Tim Peters2344fae2001-01-15 00:50:52 +0000619 return
620 # parse arguments; comma has lowest precedence
621 # and cannot occur in filename
622 filename = None
623 lineno = None
624 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000625 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000626 if comma > 0:
627 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000628 cond = arg[comma+1:].lstrip()
629 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000630 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000631 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000632 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000633 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000634 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000635 f = self.lookupmodule(filename)
636 if not f:
Georg Brandl0d089622010-07-30 16:00:46 +0000637 self.error('%r not found from sys.path' % filename)
Tim Peters2344fae2001-01-15 00:50:52 +0000638 return
639 else:
640 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000641 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000642 try:
643 lineno = int(arg)
Georg Brandlf93390a2010-10-14 07:17:44 +0000644 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000645 self.error('Bad lineno: %s' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000646 return
647 else:
648 # no colon; can be lineno or function
649 try:
650 lineno = int(arg)
651 except ValueError:
652 try:
653 func = eval(arg,
654 self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +0000655 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000656 except:
657 func = arg
658 try:
Christian Heimesff737952007-11-27 10:40:20 +0000659 if hasattr(func, '__func__'):
660 func = func.__func__
Neal Norwitz221085d2007-02-25 20:55:47 +0000661 code = func.__code__
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000662 #use co_name to identify the bkpt (function names
663 #could be aliased, but co_name is invariant)
664 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000665 lineno = code.co_firstlineno
666 filename = code.co_filename
667 except:
668 # last thing to try
669 (ok, filename, ln) = self.lineinfo(arg)
670 if not ok:
Georg Brandl0d089622010-07-30 16:00:46 +0000671 self.error('The specified object %r is not a function '
672 'or was not found along sys.path.' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000673 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000674 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000675 lineno = int(ln)
676 if not filename:
677 filename = self.defaultFile()
678 # Check for reasonable breakpoint
679 line = self.checkline(filename, lineno)
680 if line:
681 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000682 err = self.set_break(filename, line, temporary, cond, funcname)
Georg Brandl0d089622010-07-30 16:00:46 +0000683 if err:
Berker Peksagad5ffd42014-07-12 18:24:32 +0300684 self.error(err)
Tim Peters2344fae2001-01-15 00:50:52 +0000685 else:
686 bp = self.get_breaks(filename, line)[-1]
Georg Brandl0d089622010-07-30 16:00:46 +0000687 self.message("Breakpoint %d at %s:%d" %
688 (bp.number, bp.file, bp.line))
Tim Peters2344fae2001-01-15 00:50:52 +0000689
690 # To be overridden in derived debuggers
691 def defaultFile(self):
692 """Produce a reasonable default."""
693 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000694 if filename == '<string>' and self.mainpyfile:
695 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000696 return filename
697
698 do_b = do_break
699
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100700 complete_break = _complete_location
701 complete_b = _complete_location
702
Tim Peters2344fae2001-01-15 00:50:52 +0000703 def do_tbreak(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000704 """tbreak [ ([filename:]lineno | function) [, condition] ]
705 Same arguments as break, but sets a temporary breakpoint: it
706 is automatically deleted when first hit.
707 """
Tim Peters2344fae2001-01-15 00:50:52 +0000708 self.do_break(arg, 1)
709
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100710 complete_tbreak = _complete_location
711
Tim Peters2344fae2001-01-15 00:50:52 +0000712 def lineinfo(self, identifier):
713 failed = (None, None, None)
714 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000715 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000716 if len(idstring) == 1:
717 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000718 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000719 elif len(idstring) == 3:
720 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000721 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000722 else:
723 return failed
724 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000725 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000726 # Protection for derived debuggers
727 if parts[0] == 'self':
728 del parts[0]
729 if len(parts) == 0:
730 return failed
731 # Best first guess at file to look at
732 fname = self.defaultFile()
733 if len(parts) == 1:
734 item = parts[0]
735 else:
736 # More than one part.
737 # First is module, second is method/class
738 f = self.lookupmodule(parts[0])
739 if f:
740 fname = f
741 item = parts[1]
742 answer = find_function(item, fname)
743 return answer or failed
744
745 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000746 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000747
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000748 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
749 line or EOF). Warning: testing is not comprehensive.
750 """
Georg Brandl1e30bd32010-07-30 07:21:26 +0000751 # this method should be callable before starting debugging, so default
752 # to "no globals" if there is no current frame
753 globs = self.curframe.f_globals if hasattr(self, 'curframe') else None
754 line = linecache.getline(filename, lineno, globs)
Tim Peters2344fae2001-01-15 00:50:52 +0000755 if not line:
Georg Brandl0d089622010-07-30 16:00:46 +0000756 self.message('End of file')
Tim Peters2344fae2001-01-15 00:50:52 +0000757 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000758 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000759 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000760 if (not line or (line[0] == '#') or
761 (line[:3] == '"""') or line[:3] == "'''"):
Georg Brandl0d089622010-07-30 16:00:46 +0000762 self.error('Blank or comment')
Tim Peters2344fae2001-01-15 00:50:52 +0000763 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000764 return lineno
765
766 def do_enable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000767 """enable bpnumber [bpnumber ...]
768 Enables the breakpoints given as a space separated list of
769 breakpoint numbers.
770 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000771 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000772 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000773 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000774 bp = self.get_bpbynumber(i)
775 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000776 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000777 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000778 bp.enable()
Georg Brandl0d089622010-07-30 16:00:46 +0000779 self.message('Enabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000780
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100781 complete_enable = _complete_bpnumber
782
Tim Peters2344fae2001-01-15 00:50:52 +0000783 def do_disable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000784 """disable bpnumber [bpnumber ...]
785 Disables the breakpoints given as a space separated list of
786 breakpoint numbers. Disabling a breakpoint means it cannot
787 cause the program to stop execution, but unlike clearing a
788 breakpoint, it remains in the list of breakpoints and can be
789 (re-)enabled.
790 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000791 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000792 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000793 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000794 bp = self.get_bpbynumber(i)
795 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000796 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000797 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000798 bp.disable()
Georg Brandl0d089622010-07-30 16:00:46 +0000799 self.message('Disabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000800
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100801 complete_disable = _complete_bpnumber
802
Tim Peters2344fae2001-01-15 00:50:52 +0000803 def do_condition(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000804 """condition bpnumber [condition]
805 Set a new condition for the breakpoint, an expression which
806 must evaluate to true before the breakpoint is honored. If
807 condition is absent, any existing condition is removed; i.e.,
808 the breakpoint is made unconditional.
809 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000810 args = arg.split(' ', 1)
Thomas Woutersb2137042007-02-01 18:02:27 +0000811 try:
Tim Peters2344fae2001-01-15 00:50:52 +0000812 cond = args[1]
Georg Brandl7410dd12010-07-30 12:01:20 +0000813 except IndexError:
Tim Peters2344fae2001-01-15 00:50:52 +0000814 cond = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000815 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000816 bp = self.get_bpbynumber(args[0].strip())
Georg Brandl0079ffc2013-10-14 16:08:15 +0200817 except IndexError:
818 self.error('Breakpoint number expected')
Georg Brandl7410dd12010-07-30 12:01:20 +0000819 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000820 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000821 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000822 bp.cond = cond
823 if not cond:
Georg Brandl0d089622010-07-30 16:00:46 +0000824 self.message('Breakpoint %d is now unconditional.' % bp.number)
Georg Brandl7410dd12010-07-30 12:01:20 +0000825 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000826 self.message('New condition set for breakpoint %d.' % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000827
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100828 complete_condition = _complete_bpnumber
829
Georg Brandl7410dd12010-07-30 12:01:20 +0000830 def do_ignore(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000831 """ignore bpnumber [count]
832 Set the ignore count for the given breakpoint number. If
833 count is omitted, the ignore count is set to 0. A breakpoint
834 becomes active when the ignore count is zero. When non-zero,
835 the count is decremented each time the breakpoint is reached
836 and the breakpoint is not disabled and any associated
837 condition evaluates to true.
838 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000839 args = arg.split()
Thomas Woutersb2137042007-02-01 18:02:27 +0000840 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000841 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000842 except:
843 count = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +0000844 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000845 bp = self.get_bpbynumber(args[0].strip())
Georg Brandl0079ffc2013-10-14 16:08:15 +0200846 except IndexError:
847 self.error('Breakpoint number expected')
Georg Brandl7410dd12010-07-30 12:01:20 +0000848 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000849 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000850 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000851 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000852 if count > 0:
Guido van Rossum08454592002-07-12 13:10:53 +0000853 if count > 1:
Georg Brandl0d089622010-07-30 16:00:46 +0000854 countstr = '%d crossings' % count
Tim Peters2344fae2001-01-15 00:50:52 +0000855 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000856 countstr = '1 crossing'
857 self.message('Will ignore next %s of breakpoint %d.' %
858 (countstr, bp.number))
Tim Peters2344fae2001-01-15 00:50:52 +0000859 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000860 self.message('Will stop next time breakpoint %d is reached.'
861 % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000862
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100863 complete_ignore = _complete_bpnumber
864
Tim Peters2344fae2001-01-15 00:50:52 +0000865 def do_clear(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000866 """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]]
867 With a space separated list of breakpoint numbers, clear
868 those breakpoints. Without argument, clear all breaks (but
869 first ask confirmation). With a filename:lineno argument,
870 clear all breaks at that line in that file.
871 """
Tim Peters2344fae2001-01-15 00:50:52 +0000872 if not arg:
873 try:
Guido van Rossumc5b6ab02007-05-27 09:19:52 +0000874 reply = input('Clear all breaks? ')
Tim Peters2344fae2001-01-15 00:50:52 +0000875 except EOFError:
876 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000877 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000878 if reply in ('y', 'yes'):
Georg Brandl7410dd12010-07-30 12:01:20 +0000879 bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp]
Tim Peters2344fae2001-01-15 00:50:52 +0000880 self.clear_all_breaks()
Georg Brandl7410dd12010-07-30 12:01:20 +0000881 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000882 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000883 return
884 if ':' in arg:
885 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000886 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000887 filename = arg[:i]
888 arg = arg[i+1:]
889 try:
890 lineno = int(arg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000891 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000892 err = "Invalid line number (%s)" % arg
893 else:
Georg Brandl7410dd12010-07-30 12:01:20 +0000894 bplist = self.get_breaks(filename, lineno)
Tim Peters2344fae2001-01-15 00:50:52 +0000895 err = self.clear_break(filename, lineno)
Georg Brandl7410dd12010-07-30 12:01:20 +0000896 if err:
Georg Brandl0d089622010-07-30 16:00:46 +0000897 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000898 else:
899 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000900 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000901 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000902 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000903 for i in numberlist:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000904 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000905 bp = self.get_bpbynumber(i)
906 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000907 self.error(err)
Tim Peters2344fae2001-01-15 00:50:52 +0000908 else:
Senthil Kumaran6f107042010-11-29 11:54:17 +0000909 self.clear_bpbynumber(i)
Georg Brandl0d089622010-07-30 16:00:46 +0000910 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000911 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
912
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100913 complete_clear = _complete_location
914 complete_cl = _complete_location
915
Tim Peters2344fae2001-01-15 00:50:52 +0000916 def do_where(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000917 """w(here)
918 Print a stack trace, with the most recent frame at the bottom.
919 An arrow indicates the "current frame", which determines the
920 context of most commands. 'bt' is an alias for this command.
921 """
Tim Peters2344fae2001-01-15 00:50:52 +0000922 self.print_stack_trace()
923 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000924 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000925
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000926 def _select_frame(self, number):
927 assert 0 <= number < len(self.stack)
928 self.curindex = number
929 self.curframe = self.stack[self.curindex][0]
930 self.curframe_locals = self.curframe.f_locals
931 self.print_stack_entry(self.stack[self.curindex])
932 self.lineno = None
933
Tim Peters2344fae2001-01-15 00:50:52 +0000934 def do_up(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000935 """u(p) [count]
936 Move the current frame count (default one) levels up in the
937 stack trace (to an older frame).
938 """
Tim Peters2344fae2001-01-15 00:50:52 +0000939 if self.curindex == 0:
Georg Brandl0d089622010-07-30 16:00:46 +0000940 self.error('Oldest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000941 return
942 try:
943 count = int(arg or 1)
944 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000945 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000946 return
947 if count < 0:
948 newframe = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000949 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000950 newframe = max(0, self.curindex - count)
951 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000952 do_u = do_up
953
954 def do_down(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000955 """d(own) [count]
956 Move the current frame count (default one) levels down in the
957 stack trace (to a newer frame).
958 """
Tim Peters2344fae2001-01-15 00:50:52 +0000959 if self.curindex + 1 == len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +0000960 self.error('Newest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000961 return
962 try:
963 count = int(arg or 1)
964 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000965 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000966 return
967 if count < 0:
968 newframe = len(self.stack) - 1
Tim Peters2344fae2001-01-15 00:50:52 +0000969 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000970 newframe = min(len(self.stack) - 1, self.curindex + count)
971 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000972 do_d = do_down
973
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000974 def do_until(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000975 """unt(il) [lineno]
976 Without argument, continue execution until the line with a
977 number greater than the current one is reached. With a line
978 number, continue execution until a line with a number greater
979 or equal to that is reached. In both cases, also stop when
980 the current frame returns.
981 """
Georg Brandl2dfec552010-07-30 08:43:32 +0000982 if arg:
983 try:
984 lineno = int(arg)
985 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000986 self.error('Error in argument: %r' % arg)
Georg Brandl2dfec552010-07-30 08:43:32 +0000987 return
988 if lineno <= self.curframe.f_lineno:
Georg Brandl0d089622010-07-30 16:00:46 +0000989 self.error('"until" line number is smaller than current '
990 'line number')
Georg Brandl2dfec552010-07-30 08:43:32 +0000991 return
992 else:
993 lineno = None
994 self.set_until(self.curframe, lineno)
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000995 return 1
996 do_unt = do_until
997
Tim Peters2344fae2001-01-15 00:50:52 +0000998 def do_step(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000999 """s(tep)
1000 Execute the current line, stop at the first possible occasion
1001 (either in a function that is called or in the current
1002 function).
1003 """
Tim Peters2344fae2001-01-15 00:50:52 +00001004 self.set_step()
1005 return 1
1006 do_s = do_step
1007
1008 def do_next(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001009 """n(ext)
1010 Continue execution until the next line in the current function
1011 is reached or it returns.
1012 """
Tim Peters2344fae2001-01-15 00:50:52 +00001013 self.set_next(self.curframe)
1014 return 1
1015 do_n = do_next
1016
Guido van Rossumd8faa362007-04-27 19:54:29 +00001017 def do_run(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001018 """run [args...]
1019 Restart the debugged python program. If a string is supplied
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001020 it is split with "shlex", and the result is used as the new
Georg Brandl0d089622010-07-30 16:00:46 +00001021 sys.argv. History, breakpoints, actions and debugger options
1022 are preserved. "restart" is an alias for "run".
1023 """
Guido van Rossumd8faa362007-04-27 19:54:29 +00001024 if arg:
1025 import shlex
1026 argv0 = sys.argv[0:1]
1027 sys.argv = shlex.split(arg)
1028 sys.argv[:0] = argv0
Georg Brandl0d089622010-07-30 16:00:46 +00001029 # this is caught in the main debugger loop
Guido van Rossumd8faa362007-04-27 19:54:29 +00001030 raise Restart
1031
1032 do_restart = do_run
1033
Tim Peters2344fae2001-01-15 00:50:52 +00001034 def do_return(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001035 """r(eturn)
1036 Continue execution until the current function returns.
1037 """
Tim Peters2344fae2001-01-15 00:50:52 +00001038 self.set_return(self.curframe)
1039 return 1
1040 do_r = do_return
1041
1042 def do_continue(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001043 """c(ont(inue))
1044 Continue execution, only stop when a breakpoint is encountered.
1045 """
Georg Brandl44f2b642010-12-04 16:00:47 +00001046 if not self.nosigint:
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001047 try:
Xavier de Gaye10e54ae2016-10-12 20:13:24 +02001048 Pdb._previous_sigint_handler = \
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001049 signal.signal(signal.SIGINT, self.sigint_handler)
1050 except ValueError:
1051 # ValueError happens when do_continue() is invoked from
1052 # a non-main thread in which case we just continue without
1053 # SIGINT set. Would printing a message here (once) make
1054 # sense?
1055 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001056 self.set_continue()
1057 return 1
1058 do_c = do_cont = do_continue
1059
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001060 def do_jump(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001061 """j(ump) lineno
1062 Set the next line that will be executed. Only available in
1063 the bottom-most frame. This lets you jump back and execute
1064 code again, or jump forward to skip code that you don't want
1065 to run.
1066
1067 It should be noted that not all jumps are allowed -- for
1068 instance it is not possible to jump into the middle of a
1069 for loop or out of a finally clause.
1070 """
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001071 if self.curindex + 1 != len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +00001072 self.error('You can only jump within the bottom frame')
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001073 return
1074 try:
1075 arg = int(arg)
1076 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +00001077 self.error("The 'jump' command requires a line number")
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001078 else:
1079 try:
1080 # Do the jump, fix up our copy of the stack, and display the
1081 # new position
1082 self.curframe.f_lineno = arg
1083 self.stack[self.curindex] = self.stack[self.curindex][0], arg
1084 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumb940e112007-01-10 16:19:56 +00001085 except ValueError as e:
Georg Brandl0d089622010-07-30 16:00:46 +00001086 self.error('Jump failed: %s' % e)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001087 do_j = do_jump
1088
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001089 def do_debug(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001090 """debug code
1091 Enter a recursive debugger that steps through the code
1092 argument (which is an arbitrary expression or statement to be
1093 executed in the current environment).
1094 """
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001095 sys.settrace(None)
1096 globals = self.curframe.f_globals
Benjamin Petersond23f8222009-04-05 19:13:16 +00001097 locals = self.curframe_locals
Guido van Rossum7736b5b2008-01-15 21:44:53 +00001098 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +00001099 p.prompt = "(%s) " % self.prompt.strip()
Georg Brandl0d089622010-07-30 16:00:46 +00001100 self.message("ENTERING RECURSIVE DEBUGGER")
Daniel Hahler3e936432019-03-12 04:29:04 +01001101 try:
1102 sys.call_tracing(p.run, (arg, globals, locals))
1103 except Exception:
1104 exc_info = sys.exc_info()[:2]
1105 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Georg Brandl0d089622010-07-30 16:00:46 +00001106 self.message("LEAVING RECURSIVE DEBUGGER")
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001107 sys.settrace(self.trace_dispatch)
1108 self.lastcmd = p.lastcmd
1109
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001110 complete_debug = _complete_expression
1111
Tim Peters2344fae2001-01-15 00:50:52 +00001112 def do_quit(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001113 """q(uit)\nexit
1114 Quit from the debugger. The program being executed is aborted.
1115 """
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001116 self._user_requested_quit = True
Tim Peters2344fae2001-01-15 00:50:52 +00001117 self.set_quit()
1118 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001119
Tim Peters2344fae2001-01-15 00:50:52 +00001120 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +00001121 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +00001122
Guido van Rossumeef26072003-01-13 21:13:55 +00001123 def do_EOF(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001124 """EOF
1125 Handles the receipt of EOF as a command.
1126 """
1127 self.message('')
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001128 self._user_requested_quit = True
Guido van Rossumeef26072003-01-13 21:13:55 +00001129 self.set_quit()
1130 return 1
1131
Tim Peters2344fae2001-01-15 00:50:52 +00001132 def do_args(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001133 """a(rgs)
1134 Print the argument list of the current function.
1135 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001136 co = self.curframe.f_code
1137 dict = self.curframe_locals
Pablo Galindocd74e662019-06-01 18:08:04 +01001138 n = co.co_argcount + co.co_kwonlyargcount
RĂ©mi Lapeyrebf457c72019-05-21 00:17:30 +02001139 if co.co_flags & inspect.CO_VARARGS: n = n+1
1140 if co.co_flags & inspect.CO_VARKEYWORDS: n = n+1
Tim Peters2344fae2001-01-15 00:50:52 +00001141 for i in range(n):
1142 name = co.co_varnames[i]
Georg Brandl0d089622010-07-30 16:00:46 +00001143 if name in dict:
1144 self.message('%s = %r' % (name, dict[name]))
1145 else:
1146 self.message('%s = *** undefined ***' % (name,))
Tim Peters2344fae2001-01-15 00:50:52 +00001147 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +00001148
Tim Peters2344fae2001-01-15 00:50:52 +00001149 def do_retval(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001150 """retval
1151 Print the return value for the last return of a function.
1152 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001153 if '__return__' in self.curframe_locals:
Georg Brandl0d089622010-07-30 16:00:46 +00001154 self.message(repr(self.curframe_locals['__return__']))
Tim Peters2344fae2001-01-15 00:50:52 +00001155 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001156 self.error('Not yet returned!')
Tim Peters2344fae2001-01-15 00:50:52 +00001157 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +00001158
Barry Warsaw210bd202002-11-05 22:40:20 +00001159 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +00001160 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +00001161 return eval(arg, self.curframe.f_globals, self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +00001162 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001163 exc_info = sys.exc_info()[:2]
1164 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Barry Warsaw210bd202002-11-05 22:40:20 +00001165 raise
Guido van Rossum2424f851998-09-11 22:50:09 +00001166
Georg Brandlcbc79c72010-12-04 16:21:42 +00001167 def _getval_except(self, arg, frame=None):
1168 try:
1169 if frame is None:
1170 return eval(arg, self.curframe.f_globals, self.curframe_locals)
1171 else:
1172 return eval(arg, frame.f_globals, frame.f_locals)
1173 except:
1174 exc_info = sys.exc_info()[:2]
1175 err = traceback.format_exception_only(*exc_info)[-1].strip()
1176 return _rstr('** raised %s **' % err)
1177
Barry Warsaw210bd202002-11-05 22:40:20 +00001178 def do_p(self, arg):
R David Murray78d692f2013-10-10 17:23:26 -04001179 """p expression
Georg Brandl0d089622010-07-30 16:00:46 +00001180 Print the value of the expression.
1181 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001182 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001183 self.message(repr(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001184 except:
1185 pass
1186
1187 def do_pp(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001188 """pp expression
1189 Pretty-print the value of the expression.
1190 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001191 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001192 self.message(pprint.pformat(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001193 except:
1194 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001195
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001196 complete_print = _complete_expression
1197 complete_p = _complete_expression
1198 complete_pp = _complete_expression
1199
Tim Peters2344fae2001-01-15 00:50:52 +00001200 def do_list(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001201 """l(ist) [first [,last] | .]
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001202
1203 List source code for the current file. Without arguments,
1204 list 11 lines around the current line or continue the previous
1205 listing. With . as argument, list 11 lines around the current
1206 line. With one argument, list 11 lines starting at that line.
1207 With two arguments, list the given range; if the second
1208 argument is less than the first, it is a count.
1209
1210 The current line in the current frame is indicated by "->".
1211 If an exception is being debugged, the line where the
1212 exception was originally raised or propagated is indicated by
1213 ">>", if it differs from the current line.
Georg Brandl0d089622010-07-30 16:00:46 +00001214 """
Tim Peters2344fae2001-01-15 00:50:52 +00001215 self.lastcmd = 'list'
1216 last = None
Georg Brandla91a94b2010-07-30 07:14:01 +00001217 if arg and arg != '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001218 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001219 if ',' in arg:
1220 first, last = arg.split(',')
1221 first = int(first.strip())
1222 last = int(last.strip())
Tim Peters2344fae2001-01-15 00:50:52 +00001223 if last < first:
Georg Brandl0d089622010-07-30 16:00:46 +00001224 # assume it's a count
Tim Peters2344fae2001-01-15 00:50:52 +00001225 last = first + last
1226 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001227 first = int(arg.strip())
1228 first = max(1, first - 5)
1229 except ValueError:
1230 self.error('Error in argument: %r' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001231 return
Georg Brandla91a94b2010-07-30 07:14:01 +00001232 elif self.lineno is None or arg == '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001233 first = max(1, self.curframe.f_lineno - 5)
1234 else:
1235 first = self.lineno + 1
1236 if last is None:
1237 last = first + 10
1238 filename = self.curframe.f_code.co_filename
1239 breaklist = self.get_file_breaks(filename)
1240 try:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001241 lines = linecache.getlines(filename, self.curframe.f_globals)
1242 self._print_lines(lines[first-1:last], first, breaklist,
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001243 self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001244 self.lineno = min(last, len(lines))
1245 if len(lines) < last:
1246 self.message('[EOF]')
Tim Peters2344fae2001-01-15 00:50:52 +00001247 except KeyboardInterrupt:
1248 pass
1249 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +00001250
Georg Brandle59ca2a2010-07-30 17:04:28 +00001251 def do_longlist(self, arg):
1252 """longlist | ll
1253 List the whole source code for the current function or frame.
1254 """
1255 filename = self.curframe.f_code.co_filename
1256 breaklist = self.get_file_breaks(filename)
1257 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001258 lines, lineno = getsourcelines(self.curframe)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001259 except OSError as err:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001260 self.error(err)
1261 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001262 self._print_lines(lines, lineno, breaklist, self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001263 do_ll = do_longlist
1264
1265 def do_source(self, arg):
1266 """source expression
1267 Try to get source code for the given object and display it.
1268 """
1269 try:
1270 obj = self._getval(arg)
1271 except:
1272 return
1273 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001274 lines, lineno = getsourcelines(obj)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001275 except (OSError, TypeError) as err:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001276 self.error(err)
1277 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001278 self._print_lines(lines, lineno)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001279
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001280 complete_source = _complete_expression
1281
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001282 def _print_lines(self, lines, start, breaks=(), frame=None):
Georg Brandle59ca2a2010-07-30 17:04:28 +00001283 """Print a range of lines."""
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001284 if frame:
1285 current_lineno = frame.f_lineno
1286 exc_lineno = self.tb_lineno.get(frame, -1)
1287 else:
1288 current_lineno = exc_lineno = -1
Georg Brandle59ca2a2010-07-30 17:04:28 +00001289 for lineno, line in enumerate(lines, start):
1290 s = str(lineno).rjust(3)
1291 if len(s) < 4:
1292 s += ' '
1293 if lineno in breaks:
1294 s += 'B'
1295 else:
1296 s += ' '
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001297 if lineno == current_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001298 s += '->'
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001299 elif lineno == exc_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001300 s += '>>'
1301 self.message(s + '\t' + line.rstrip())
1302
Tim Peters2344fae2001-01-15 00:50:52 +00001303 def do_whatis(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001304 """whatis arg
1305 Print the type of the argument.
1306 """
Tim Peters2344fae2001-01-15 00:50:52 +00001307 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001308 value = self._getval(arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001309 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001310 # _getval() already printed the error
Tim Peters2344fae2001-01-15 00:50:52 +00001311 return
1312 code = None
1313 # Is it a function?
Georg Brandl0d089622010-07-30 16:00:46 +00001314 try:
1315 code = value.__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('Function %s' % code.co_name)
Tim Peters2344fae2001-01-15 00:50:52 +00001320 return
1321 # Is it an instance method?
Georg Brandl0d089622010-07-30 16:00:46 +00001322 try:
1323 code = value.__func__.__code__
1324 except Exception:
1325 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001326 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001327 self.message('Method %s' % code.co_name)
1328 return
1329 # Is it a class?
1330 if value.__class__ is type:
Serhiy Storchaka521e5862014-07-22 15:00:37 +03001331 self.message('Class %s.%s' % (value.__module__, value.__qualname__))
Tim Peters2344fae2001-01-15 00:50:52 +00001332 return
1333 # None of the above...
Georg Brandl0d089622010-07-30 16:00:46 +00001334 self.message(type(value))
Guido van Rossum8e2ec561993-07-29 09:37:38 +00001335
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001336 complete_whatis = _complete_expression
1337
Georg Brandlcbc79c72010-12-04 16:21:42 +00001338 def do_display(self, arg):
1339 """display [expression]
1340
1341 Display the value of the expression if it changed, each time execution
1342 stops in the current frame.
1343
1344 Without expression, list all display expressions for the current frame.
1345 """
1346 if not arg:
1347 self.message('Currently displaying:')
1348 for item in self.displaying.get(self.curframe, {}).items():
1349 self.message('%s: %r' % item)
1350 else:
1351 val = self._getval_except(arg)
1352 self.displaying.setdefault(self.curframe, {})[arg] = val
1353 self.message('display %s: %r' % (arg, val))
1354
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001355 complete_display = _complete_expression
1356
Georg Brandlcbc79c72010-12-04 16:21:42 +00001357 def do_undisplay(self, arg):
1358 """undisplay [expression]
1359
1360 Do not display the expression any more in the current frame.
1361
1362 Without expression, clear all display expressions for the current frame.
1363 """
1364 if arg:
1365 try:
1366 del self.displaying.get(self.curframe, {})[arg]
1367 except KeyError:
1368 self.error('not displaying %s' % arg)
1369 else:
1370 self.displaying.pop(self.curframe, None)
1371
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001372 def complete_undisplay(self, text, line, begidx, endidx):
1373 return [e for e in self.displaying.get(self.curframe, {})
1374 if e.startswith(text)]
1375
Georg Brandl1acb7462010-12-04 11:20:26 +00001376 def do_interact(self, arg):
1377 """interact
1378
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001379 Start an interactive interpreter whose global namespace
Georg Brandl1acb7462010-12-04 11:20:26 +00001380 contains all the (global and local) names found in the current scope.
1381 """
Serhiy Storchakada084702019-03-27 08:02:28 +02001382 ns = {**self.curframe.f_globals, **self.curframe_locals}
Georg Brandl1acb7462010-12-04 11:20:26 +00001383 code.interact("*interactive*", local=ns)
1384
Tim Peters2344fae2001-01-15 00:50:52 +00001385 def do_alias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001386 """alias [name [command [parameter parameter ...] ]]
1387 Create an alias called 'name' that executes 'command'. The
1388 command must *not* be enclosed in quotes. Replaceable
1389 parameters can be indicated by %1, %2, and so on, while %* is
1390 replaced by all the parameters. If no command is given, the
1391 current alias for name is shown. If no name is given, all
1392 aliases are listed.
1393
1394 Aliases may be nested and can contain anything that can be
1395 legally typed at the pdb prompt. Note! You *can* override
1396 internal pdb commands with aliases! Those internal commands
1397 are then hidden until the alias is removed. Aliasing is
1398 recursively applied to the first word of the command line; all
1399 other words in the line are left alone.
1400
1401 As an example, here are two useful aliases (especially when
1402 placed in the .pdbrc file):
1403
1404 # Print instance variables (usage "pi classInst")
R David Murray78d692f2013-10-10 17:23:26 -04001405 alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])
Georg Brandl0d089622010-07-30 16:00:46 +00001406 # Print instance variables in self
1407 alias ps pi self
1408 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001409 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001410 if len(args) == 0:
Benjamin Petersonbe74a372009-09-11 21:17:13 +00001411 keys = sorted(self.aliases.keys())
Tim Peters2344fae2001-01-15 00:50:52 +00001412 for alias in keys:
Georg Brandl0d089622010-07-30 16:00:46 +00001413 self.message("%s = %s" % (alias, self.aliases[alias]))
Tim Peters2344fae2001-01-15 00:50:52 +00001414 return
Guido van Rossum08454592002-07-12 13:10:53 +00001415 if args[0] in self.aliases and len(args) == 1:
Georg Brandl0d089622010-07-30 16:00:46 +00001416 self.message("%s = %s" % (args[0], self.aliases[args[0]]))
Tim Peters2344fae2001-01-15 00:50:52 +00001417 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001418 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +00001419
Tim Peters2344fae2001-01-15 00:50:52 +00001420 def do_unalias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001421 """unalias name
1422 Delete the specified alias.
1423 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001424 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001425 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +00001426 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +00001427 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +00001428
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001429 def complete_unalias(self, text, line, begidx, endidx):
1430 return [a for a in self.aliases if a.startswith(text)]
1431
Georg Brandl0d089622010-07-30 16:00:46 +00001432 # List of all the commands making the program resume execution.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001433 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
1434 'do_quit', 'do_jump']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001435
Tim Peters2344fae2001-01-15 00:50:52 +00001436 # Print a traceback starting at the top stack frame.
1437 # The most recently entered frame is printed last;
1438 # this is different from dbx and gdb, but consistent with
1439 # the Python interpreter's stack trace.
1440 # It is also consistent with the up/down commands (which are
1441 # compatible with dbx and gdb: up moves towards 'main()'
1442 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +00001443
Tim Peters2344fae2001-01-15 00:50:52 +00001444 def print_stack_trace(self):
1445 try:
1446 for frame_lineno in self.stack:
1447 self.print_stack_entry(frame_lineno)
1448 except KeyboardInterrupt:
1449 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001450
Tim Peters2344fae2001-01-15 00:50:52 +00001451 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
1452 frame, lineno = frame_lineno
1453 if frame is self.curframe:
Georg Brandl0d089622010-07-30 16:00:46 +00001454 prefix = '> '
Tim Peters2344fae2001-01-15 00:50:52 +00001455 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001456 prefix = ' '
1457 self.message(prefix +
1458 self.format_stack_entry(frame_lineno, prompt_prefix))
Guido van Rossum2424f851998-09-11 22:50:09 +00001459
Georg Brandl0d089622010-07-30 16:00:46 +00001460 # Provide help
Guido van Rossum921c8241992-01-10 14:54:42 +00001461
Georg Brandl0d089622010-07-30 16:00:46 +00001462 def do_help(self, arg):
1463 """h(elp)
1464 Without argument, print the list of available commands.
1465 With a command name as argument, print help about that command.
1466 "help pdb" shows the full pdb documentation.
1467 "help exec" gives help on the ! command.
1468 """
1469 if not arg:
1470 return cmd.Cmd.do_help(self, arg)
1471 try:
1472 try:
1473 topic = getattr(self, 'help_' + arg)
1474 return topic()
1475 except AttributeError:
1476 command = getattr(self, 'do_' + arg)
1477 except AttributeError:
1478 self.error('No help for %r' % arg)
1479 else:
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001480 if sys.flags.optimize >= 2:
1481 self.error('No help for %r; please do not run Python with -OO '
1482 'if you need command help' % arg)
1483 return
Georg Brandl0d089622010-07-30 16:00:46 +00001484 self.message(command.__doc__.rstrip())
Guido van Rossum921c8241992-01-10 14:54:42 +00001485
Georg Brandl0d089622010-07-30 16:00:46 +00001486 do_h = do_help
Barry Warsaw210bd202002-11-05 22:40:20 +00001487
Tim Peters2344fae2001-01-15 00:50:52 +00001488 def help_exec(self):
Georg Brandl0d089622010-07-30 16:00:46 +00001489 """(!) statement
1490 Execute the (one-line) statement in the context of the current
1491 stack frame. The exclamation point can be omitted unless the
1492 first word of the statement resembles a debugger command. To
1493 assign to a global variable you must always prefix the command
1494 with a 'global' command, e.g.:
1495 (Pdb) global list_options; list_options = ['-l']
1496 (Pdb)
1497 """
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001498 self.message((self.help_exec.__doc__ or '').strip())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001499
Tim Peters2344fae2001-01-15 00:50:52 +00001500 def help_pdb(self):
1501 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001502
Georg Brandl0d089622010-07-30 16:00:46 +00001503 # other helper functions
1504
Tim Peters2344fae2001-01-15 00:50:52 +00001505 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001506 """Helper function for break/clear parsing -- may be overridden.
1507
1508 lookupmodule() translates (possibly incomplete) file or module name
1509 into an absolute file name.
1510 """
1511 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001512 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001513 f = os.path.join(sys.path[0], filename)
1514 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1515 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001516 root, ext = os.path.splitext(filename)
1517 if ext == '':
1518 filename = filename + '.py'
1519 if os.path.isabs(filename):
1520 return filename
1521 for dirname in sys.path:
1522 while os.path.islink(dirname):
1523 dirname = os.readlink(dirname)
1524 fullname = os.path.join(dirname, filename)
1525 if os.path.exists(fullname):
1526 return fullname
1527 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001528
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001529 def _runmodule(self, module_name):
1530 self._wait_for_mainpyfile = True
1531 self._user_requested_quit = False
1532 import runpy
1533 mod_name, mod_spec, code = runpy._get_module_details(module_name)
1534 self.mainpyfile = self.canonic(code.co_filename)
1535 import __main__
1536 __main__.__dict__.clear()
1537 __main__.__dict__.update({
1538 "__name__": "__main__",
1539 "__file__": self.mainpyfile,
Mario Corchero38bfa842018-02-03 06:40:11 +00001540 "__package__": mod_spec.parent,
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001541 "__loader__": mod_spec.loader,
1542 "__spec__": mod_spec,
1543 "__builtins__": __builtins__,
1544 })
1545 self.run(code)
1546
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001547 def _runscript(self, filename):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001548 # The script has to run in __main__ namespace (or imports from
1549 # __main__ will break).
1550 #
1551 # So we clear up the __main__ and set several special variables
1552 # (this gets rid of pdb's globals and cleans old variables on restarts).
1553 import __main__
1554 __main__.__dict__.clear()
1555 __main__.__dict__.update({"__name__" : "__main__",
1556 "__file__" : filename,
1557 "__builtins__": __builtins__,
1558 })
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001559
1560 # When bdb sets tracing, a number of call and line events happens
1561 # BEFORE debugger even reaches user's code (and the exact sequence of
1562 # events depends on python version). So we take special measures to
1563 # avoid stopping before we reach the main script (see user_line and
1564 # user_call for details).
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001565 self._wait_for_mainpyfile = True
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001566 self.mainpyfile = self.canonic(filename)
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001567 self._user_requested_quit = False
Georg Brandld07ac642009-08-13 07:50:57 +00001568 with open(filename, "rb") as fp:
1569 statement = "exec(compile(%r, %r, 'exec'))" % \
1570 (fp.read(), self.mainpyfile)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001571 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001572
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001573# Collect all command help into docstring, if not run with -OO
Georg Brandl0d089622010-07-30 16:00:46 +00001574
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001575if __doc__ is not None:
1576 # unfortunately we can't guess this order from the class definition
1577 _help_order = [
1578 'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable',
1579 'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until',
1580 'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist',
R David Murray78d692f2013-10-10 17:23:26 -04001581 'args', 'p', 'pp', 'whatis', 'source', 'display', 'undisplay',
Georg Brandlcbc79c72010-12-04 16:21:42 +00001582 'interact', 'alias', 'unalias', 'debug', 'quit',
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001583 ]
Georg Brandl0d089622010-07-30 16:00:46 +00001584
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001585 for _command in _help_order:
1586 __doc__ += getattr(Pdb, 'do_' + _command).__doc__.strip() + '\n\n'
1587 __doc__ += Pdb.help_exec.__doc__
Georg Brandl0d089622010-07-30 16:00:46 +00001588
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001589 del _help_order, _command
1590
Georg Brandl0d089622010-07-30 16:00:46 +00001591
Guido van Rossum35771131992-09-08 11:59:04 +00001592# Simplified interface
1593
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001594def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001595 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001596
1597def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001598 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001599
1600def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001601 # B/W compatibility
1602 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001603
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001604def runcall(*args, **kwds):
1605 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001606
Barry Warsaw35425d62017-09-22 12:29:42 -04001607def set_trace(*, header=None):
1608 pdb = Pdb()
1609 if header is not None:
1610 pdb.message(header)
1611 pdb.set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001612
1613# Post-Mortem interface
1614
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001615def post_mortem(t=None):
1616 # handling the default
1617 if t is None:
1618 # sys.exc_info() returns (type, value, traceback) if an exception is
1619 # being handled, otherwise it returns None
1620 t = sys.exc_info()[2]
Georg Brandl0d089622010-07-30 16:00:46 +00001621 if t is None:
1622 raise ValueError("A valid traceback must be passed if no "
1623 "exception is being handled")
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001624
Tim Peters2344fae2001-01-15 00:50:52 +00001625 p = Pdb()
1626 p.reset()
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001627 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001628
1629def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001630 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001631
1632
1633# Main program for testing
1634
Guido van Rossum23efba41992-01-27 16:58:47 +00001635TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001636
Guido van Rossum921c8241992-01-10 14:54:42 +00001637def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001638 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001639
1640# print help
1641def help():
Georg Brandl02053ee2010-07-18 10:11:03 +00001642 import pydoc
1643 pydoc.pager(__doc__)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001644
Georg Brandle0230912010-07-30 08:29:39 +00001645_usage = """\
Mario Corcherofcf8b4c2018-01-28 04:58:47 +00001646usage: pdb.py [-c command] ... [-m module | pyfile] [arg] ...
Georg Brandle0230912010-07-30 08:29:39 +00001647
Mario Corcherofcf8b4c2018-01-28 04:58:47 +00001648Debug the Python program given by pyfile. Alternatively,
1649an executable module or package to debug can be specified using
1650the -m switch.
Georg Brandle0230912010-07-30 08:29:39 +00001651
1652Initial commands are read from .pdbrc files in your home directory
1653and in the current directory, if they exist. Commands supplied with
1654-c are executed after commands from .pdbrc files.
1655
1656To let the script run until an exception occurs, use "-c continue".
Georg Brandl2dfec552010-07-30 08:43:32 +00001657To let the script run up to a given line X in the debugged file, use
1658"-c 'until X'"."""
Georg Brandle0230912010-07-30 08:29:39 +00001659
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001660def main():
Georg Brandle0230912010-07-30 08:29:39 +00001661 import getopt
1662
Miss Islington (bot)21bfff92019-09-12 09:05:52 -07001663 opts, args = getopt.getopt(sys.argv[1:], 'mhc:', ['help', 'command='])
Georg Brandle0230912010-07-30 08:29:39 +00001664
1665 if not args:
1666 print(_usage)
Tim Peters2344fae2001-01-15 00:50:52 +00001667 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001668
Georg Brandle0230912010-07-30 08:29:39 +00001669 commands = []
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001670 run_as_module = False
Georg Brandle0230912010-07-30 08:29:39 +00001671 for opt, optarg in opts:
1672 if opt in ['-h', '--help']:
1673 print(_usage)
1674 sys.exit()
1675 elif opt in ['-c', '--command']:
1676 commands.append(optarg)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001677 elif opt in ['-m']:
1678 run_as_module = True
Georg Brandle0230912010-07-30 08:29:39 +00001679
1680 mainpyfile = args[0] # Get script filename
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001681 if not run_as_module and not os.path.exists(mainpyfile):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001682 print('Error:', mainpyfile, 'does not exist')
Tim Peters2344fae2001-01-15 00:50:52 +00001683 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001684
Georg Brandle0230912010-07-30 08:29:39 +00001685 sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001686
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001687 # Replace pdb's dir with script's dir in front of module search path.
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001688 if not run_as_module:
1689 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001690
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001691 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1692 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl3078df02009-05-05 09:11:31 +00001693 # changed by the user from the command line. There is a "restart" command
1694 # which allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001695 pdb = Pdb()
Georg Brandle0230912010-07-30 08:29:39 +00001696 pdb.rcLines.extend(commands)
Georg Brandl1e30bd32010-07-30 07:21:26 +00001697 while True:
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001698 try:
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001699 if run_as_module:
1700 pdb._runmodule(mainpyfile)
1701 else:
1702 pdb._runscript(mainpyfile)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001703 if pdb._user_requested_quit:
1704 break
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001705 print("The program finished and will be restarted")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001706 except Restart:
1707 print("Restarting", mainpyfile, "with arguments:")
Georg Brandle0230912010-07-30 08:29:39 +00001708 print("\t" + " ".join(args))
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001709 except SystemExit:
1710 # In most cases SystemExit does not warrant a post-mortem session.
Georg Brandle0230912010-07-30 08:29:39 +00001711 print("The program exited via sys.exit(). Exit status:", end=' ')
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001712 print(sys.exc_info()[1])
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001713 except SyntaxError:
1714 traceback.print_exc()
1715 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001716 except:
1717 traceback.print_exc()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001718 print("Uncaught exception. Entering post mortem debugging")
1719 print("Running 'cont' or 'step' will restart the program")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001720 t = sys.exc_info()[2]
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001721 pdb.interaction(None, t)
Georg Brandl3078df02009-05-05 09:11:31 +00001722 print("Post mortem debugger finished. The " + mainpyfile +
1723 " will be restarted")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001724
1725
1726# When invoked as main program, invoke the debugger on a script
Guido van Rossumd8faa362007-04-27 19:54:29 +00001727if __name__ == '__main__':
1728 import pdb
1729 pdb.main()