blob: a888a0a287f9c2c50d1c5ef1fb382a77b0f70ea9 [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
jsnkllnd5938812019-11-12 17:42:47 -050071import io
Georg Brandl44f2b642010-12-04 16:00:47 +000072import re
Guido van Rossum921c8241992-01-10 14:54:42 +000073import sys
Guido van Rossum23efba41992-01-27 16:58:47 +000074import cmd
75import bdb
Georg Brandl0a9c3e92010-07-30 18:46:38 +000076import dis
Georg Brandl1acb7462010-12-04 11:20:26 +000077import code
Georg Brandl4c7c3c52012-03-10 22:36:48 +010078import glob
Barry Warsaw210bd202002-11-05 22:40:20 +000079import pprint
Georg Brandl44f2b642010-12-04 16:00:47 +000080import signal
Georg Brandle59ca2a2010-07-30 17:04:28 +000081import inspect
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +030082import tokenize
Georg Brandl1acb7462010-12-04 11:20:26 +000083import traceback
84import linecache
Guido van Rossumd8faa362007-04-27 19:54:29 +000085
86
87class Restart(Exception):
88 """Causes a debugger to be restarted for the debugged python program."""
89 pass
90
Skip Montanaro352674d2001-02-07 23:14:30 +000091__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
92 "post_mortem", "help"]
93
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000094def find_function(funcname, filename):
Thomas Wouters89f507f2006-12-13 04:49:30 +000095 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
Tim Peters2344fae2001-01-15 00:50:52 +000096 try:
Serhiy Storchaka19fcffa2020-06-21 11:07:50 +030097 fp = tokenize.open(filename)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +020098 except OSError:
Tim Peters2344fae2001-01-15 00:50:52 +000099 return None
100 # consumer of this info expects the first line to be 1
Georg Brandl6e220552013-10-13 20:51:47 +0200101 with fp:
102 for lineno, line in enumerate(fp, start=1):
103 if cre.match(line):
104 return funcname, filename, lineno
105 return None
Guido van Rossum921c8241992-01-10 14:54:42 +0000106
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000107def getsourcelines(obj):
108 lines, lineno = inspect.findsource(obj)
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000109 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000110 # must be a module frame: do not try to cut a block out of it
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000111 return lines, 1
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000112 elif inspect.ismodule(obj):
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000113 return lines, 1
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000114 return inspect.getblock(lines[lineno:]), lineno+1
Guido van Rossum921c8241992-01-10 14:54:42 +0000115
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000116def lasti2lineno(code, lasti):
117 linestarts = list(dis.findlinestarts(code))
118 linestarts.reverse()
119 for i, lineno in linestarts:
120 if lasti >= i:
121 return lineno
122 return 0
123
124
Georg Brandlcbc79c72010-12-04 16:21:42 +0000125class _rstr(str):
126 """String that doesn't quote its repr."""
127 def __repr__(self):
128 return self
129
130
Guido van Rossuma558e371994-11-10 22:27:35 +0000131# Interaction prompt line will separate file and call info from code
132# text using value of line_prefix string. A newline and arrow may
133# be to your liking. You can set it once pdb is imported using the
134# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +0000135# line_prefix = ': ' # Use this to get the old situation back
136line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +0000137
Guido van Rossum23efba41992-01-27 16:58:47 +0000138class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +0000139
Xavier de Gaye10e54ae2016-10-12 20:13:24 +0200140 _previous_sigint_handler = None
141
Georg Brandl44f2b642010-12-04 16:00:47 +0000142 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None,
Ɓukasz Langa2eb6eca2016-09-09 22:21:17 -0700143 nosigint=False, readrc=True):
Georg Brandl243ad662009-05-05 09:00:19 +0000144 bdb.Bdb.__init__(self, skip=skip)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000145 cmd.Cmd.__init__(self, completekey, stdin, stdout)
Steve Dower60419a72019-06-24 08:42:54 -0700146 sys.audit("pdb.Pdb")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000147 if stdout:
148 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000149 self.prompt = '(Pdb) '
150 self.aliases = {}
Georg Brandlcbc79c72010-12-04 16:21:42 +0000151 self.displaying = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000152 self.mainpyfile = ''
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000153 self._wait_for_mainpyfile = False
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000154 self.tb_lineno = {}
Tim Peters2344fae2001-01-15 00:50:52 +0000155 # Try to load readline if it exists
156 try:
157 import readline
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100158 # remove some common file name delimiters
159 readline.set_completer_delims(' \t\n`@#$%^&*()=+[{]}\\|;:\'",<>?')
Brett Cannoncd171c82013-07-04 17:43:24 -0400160 except ImportError:
Tim Peters2344fae2001-01-15 00:50:52 +0000161 pass
Georg Brandl44f2b642010-12-04 16:00:47 +0000162 self.allow_kbdint = False
163 self.nosigint = nosigint
Guido van Rossum2424f851998-09-11 22:50:09 +0000164
Timothy Hopper7ea9a852019-08-02 18:20:14 -0400165 # Read ~/.pdbrc and ./.pdbrc
Tim Peters2344fae2001-01-15 00:50:52 +0000166 self.rcLines = []
Ɓukasz Langa2eb6eca2016-09-09 22:21:17 -0700167 if readrc:
Timothy Hopper7ea9a852019-08-02 18:20:14 -0400168 try:
169 with open(os.path.expanduser('~/.pdbrc')) as rcFile:
170 self.rcLines.extend(rcFile)
171 except OSError:
172 pass
Tim Peters2344fae2001-01-15 00:50:52 +0000173 try:
Ɓukasz Langa2eb6eca2016-09-09 22:21:17 -0700174 with open(".pdbrc") as rcFile:
Florent Xicluna7dde7922010-09-03 19:52:03 +0000175 self.rcLines.extend(rcFile)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200176 except OSError:
Tim Peters2344fae2001-01-15 00:50:52 +0000177 pass
Guido van Rossum23efba41992-01-27 16:58:47 +0000178
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000179 self.commands = {} # associates a command list to breakpoint numbers
Benjamin Petersond23f8222009-04-05 19:13:16 +0000180 self.commands_doprompt = {} # for each bp num, tells if the prompt
181 # must be disp. after execing the cmd list
182 self.commands_silent = {} # for each bp num, tells if the stack trace
183 # must be disp. after execing the cmd list
184 self.commands_defining = False # True while in the process of defining
185 # a command list
186 self.commands_bnum = None # The breakpoint number for which we are
187 # defining a list
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000188
Georg Brandl44f2b642010-12-04 16:00:47 +0000189 def sigint_handler(self, signum, frame):
190 if self.allow_kbdint:
191 raise KeyboardInterrupt
192 self.message("\nProgram interrupted. (Use 'cont' to resume).")
193 self.set_step()
194 self.set_trace(frame)
Georg Brandl44f2b642010-12-04 16:00:47 +0000195
Tim Peters2344fae2001-01-15 00:50:52 +0000196 def reset(self):
197 bdb.Bdb.reset(self)
198 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000199
Tim Peters2344fae2001-01-15 00:50:52 +0000200 def forget(self):
201 self.lineno = None
202 self.stack = []
203 self.curindex = 0
204 self.curframe = None
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000205 self.tb_lineno.clear()
Guido van Rossum2424f851998-09-11 22:50:09 +0000206
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000207 def setup(self, f, tb):
Tim Peters2344fae2001-01-15 00:50:52 +0000208 self.forget()
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000209 self.stack, self.curindex = self.get_stack(f, tb)
210 while tb:
211 # when setting up post-mortem debugging with a traceback, save all
212 # the original line numbers to be displayed along the current line
213 # numbers (which can be different, e.g. due to finally clauses)
214 lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti)
215 self.tb_lineno[tb.tb_frame] = lineno
216 tb = tb.tb_next
Tim Peters2344fae2001-01-15 00:50:52 +0000217 self.curframe = self.stack[self.curindex][0]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000218 # The f_locals dictionary is updated from the actual frame
219 # locals whenever the .f_locals accessor is called, so we
220 # cache it here to ensure that modifications are not overwritten.
221 self.curframe_locals = self.curframe.f_locals
Georg Brandle0230912010-07-30 08:29:39 +0000222 return self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000223
Tim Peters2344fae2001-01-15 00:50:52 +0000224 # Can be executed earlier than 'setup' if desired
225 def execRcLines(self):
Georg Brandle0230912010-07-30 08:29:39 +0000226 if not self.rcLines:
227 return
228 # local copy because of recursion
229 rcLines = self.rcLines
230 rcLines.reverse()
231 # execute every line only once
232 self.rcLines = []
233 while rcLines:
234 line = rcLines.pop().strip()
235 if line and line[0] != '#':
236 if self.onecmd(line):
237 # if onecmd returns True, the command wants to exit
238 # from the interaction, save leftover rc lines
239 # to execute before next interaction
240 self.rcLines += reversed(rcLines)
241 return True
Guido van Rossum2424f851998-09-11 22:50:09 +0000242
Tim Peters280488b2002-08-23 18:19:30 +0000243 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000244
245 def user_call(self, frame, argument_list):
246 """This method is called when there is the remote possibility
247 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000248 if self._wait_for_mainpyfile:
249 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000250 if self.stop_here(frame):
Georg Brandl0d089622010-07-30 16:00:46 +0000251 self.message('--Call--')
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000252 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000253
Tim Peters2344fae2001-01-15 00:50:52 +0000254 def user_line(self, frame):
255 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000256 if self._wait_for_mainpyfile:
257 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000258 or frame.f_lineno <= 0):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000259 return
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000260 self._wait_for_mainpyfile = False
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000261 if self.bp_commands(frame):
262 self.interaction(frame, None)
263
Georg Brandle0230912010-07-30 08:29:39 +0000264 def bp_commands(self, frame):
Georg Brandl3078df02009-05-05 09:11:31 +0000265 """Call every command that was set for the current active breakpoint
266 (if there is one).
267
268 Returns True if the normal interaction function must be called,
269 False otherwise."""
270 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
271 if getattr(self, "currentbp", False) and \
272 self.currentbp in self.commands:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000273 currentbp = self.currentbp
274 self.currentbp = 0
275 lastcmd_back = self.lastcmd
276 self.setup(frame, None)
277 for line in self.commands[currentbp]:
278 self.onecmd(line)
279 self.lastcmd = lastcmd_back
280 if not self.commands_silent[currentbp]:
281 self.print_stack_entry(self.stack[self.curindex])
282 if self.commands_doprompt[currentbp]:
Georg Brandl44f2b642010-12-04 16:00:47 +0000283 self._cmdloop()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000284 self.forget()
285 return
286 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000287
Tim Peters2344fae2001-01-15 00:50:52 +0000288 def user_return(self, frame, return_value):
289 """This function is called when a return trap is set here."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000290 if self._wait_for_mainpyfile:
291 return
Tim Peters2344fae2001-01-15 00:50:52 +0000292 frame.f_locals['__return__'] = return_value
Georg Brandl0d089622010-07-30 16:00:46 +0000293 self.message('--Return--')
Tim Peters2344fae2001-01-15 00:50:52 +0000294 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000295
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000296 def user_exception(self, frame, exc_info):
Tim Peters2344fae2001-01-15 00:50:52 +0000297 """This function is called if an exception occurs,
298 but only if we are to stop at or just below this level."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000299 if self._wait_for_mainpyfile:
300 return
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000301 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000302 frame.f_locals['__exception__'] = exc_type, exc_value
Guido van Rossum8820c232013-11-21 11:30:06 -0800303
304 # An 'Internal StopIteration' exception is an exception debug event
305 # issued by the interpreter when handling a subgenerator run with
Martin Panter46f50722016-05-26 05:35:26 +0000306 # 'yield from' or a generator controlled by a for loop. No exception has
Berker Peksagf23530f2014-10-19 18:04:38 +0300307 # actually occurred in this case. The debugger uses this debug event to
Guido van Rossum8820c232013-11-21 11:30:06 -0800308 # stop when the debuggee is returning from such generators.
309 prefix = 'Internal ' if (not exc_traceback
310 and exc_type is StopIteration) else ''
311 self.message('%s%s' % (prefix,
312 traceback.format_exception_only(exc_type, exc_value)[-1].strip()))
Tim Peters2344fae2001-01-15 00:50:52 +0000313 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000314
Tim Peters2344fae2001-01-15 00:50:52 +0000315 # General interaction function
Georg Brandl44f2b642010-12-04 16:00:47 +0000316 def _cmdloop(self):
317 while True:
318 try:
319 # keyboard interrupts allow for an easy way to cancel
320 # the current command, so allow them during interactive input
321 self.allow_kbdint = True
322 self.cmdloop()
323 self.allow_kbdint = False
324 break
325 except KeyboardInterrupt:
326 self.message('--KeyboardInterrupt--')
Tim Peters2344fae2001-01-15 00:50:52 +0000327
Georg Brandlcbc79c72010-12-04 16:21:42 +0000328 # Called before loop, handles display expressions
329 def preloop(self):
330 displaying = self.displaying.get(self.curframe)
331 if displaying:
332 for expr, oldvalue in displaying.items():
333 newvalue = self._getval_except(expr)
334 # check for identity first; this prevents custom __eq__ to
335 # be called at every loop, and also prevents instances whose
336 # fields are changed to be displayed
337 if newvalue is not oldvalue and newvalue != oldvalue:
338 displaying[expr] = newvalue
339 self.message('display %s: %r [old: %r]' %
340 (expr, newvalue, oldvalue))
341
Tim Peters2344fae2001-01-15 00:50:52 +0000342 def interaction(self, frame, traceback):
Xavier de Gaye10e54ae2016-10-12 20:13:24 +0200343 # Restore the previous signal handler at the Pdb prompt.
344 if Pdb._previous_sigint_handler:
Daniel Hahler8d64bfa2019-09-09 12:45:58 +0200345 try:
346 signal.signal(signal.SIGINT, Pdb._previous_sigint_handler)
347 except ValueError: # ValueError: signal only works in main thread
348 pass
349 else:
350 Pdb._previous_sigint_handler = None
Georg Brandle0230912010-07-30 08:29:39 +0000351 if self.setup(frame, traceback):
352 # no interaction desired at this time (happens if .pdbrc contains
353 # a command like "continue")
354 self.forget()
355 return
Tim Peters2344fae2001-01-15 00:50:52 +0000356 self.print_stack_entry(self.stack[self.curindex])
Georg Brandl44f2b642010-12-04 16:00:47 +0000357 self._cmdloop()
Tim Peters2344fae2001-01-15 00:50:52 +0000358 self.forget()
359
Benjamin Petersond23f8222009-04-05 19:13:16 +0000360 def displayhook(self, obj):
361 """Custom displayhook for the exec in default(), which prevents
362 assignment of the _ variable in the builtins.
363 """
Georg Brandl9fa2e022009-09-16 16:40:45 +0000364 # reproduce the behavior of the standard displayhook, not printing None
365 if obj is not None:
Georg Brandl0d089622010-07-30 16:00:46 +0000366 self.message(repr(obj))
Benjamin Petersond23f8222009-04-05 19:13:16 +0000367
Tim Peters2344fae2001-01-15 00:50:52 +0000368 def default(self, line):
369 if line[:1] == '!': line = line[1:]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000370 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000371 globals = self.curframe.f_globals
372 try:
373 code = compile(line + '\n', '<stdin>', 'single')
Christian Heimes679db4a2008-01-18 09:56:22 +0000374 save_stdout = sys.stdout
375 save_stdin = sys.stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000376 save_displayhook = sys.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000377 try:
378 sys.stdin = self.stdin
379 sys.stdout = self.stdout
Benjamin Petersond23f8222009-04-05 19:13:16 +0000380 sys.displayhook = self.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000381 exec(code, globals, locals)
382 finally:
383 sys.stdout = save_stdout
384 sys.stdin = save_stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000385 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000386 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000387 exc_info = sys.exc_info()[:2]
388 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000389
390 def precmd(self, line):
391 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000392 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000393 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000394 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000395 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000396 line = self.aliases[args[0]]
397 ii = 1
398 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000399 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000400 tmpArg)
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000401 ii += 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000402 line = line.replace("%*", ' '.join(args[1:]))
403 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000404 # split into ';;' separated commands
405 # unless it's an alias command
406 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000407 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000408 if marker >= 0:
409 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000410 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000411 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000412 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000413 return line
414
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000415 def onecmd(self, line):
416 """Interpret the argument as though it had been typed in response
417 to the prompt.
418
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000419 Checks whether this line is typed at the normal prompt or in
420 a breakpoint command list definition.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000421 """
422 if not self.commands_defining:
423 return cmd.Cmd.onecmd(self, line)
424 else:
425 return self.handle_command_def(line)
426
Georg Brandlb90ffd82010-07-30 22:20:16 +0000427 def handle_command_def(self, line):
Georg Brandl44f8bf92010-07-30 08:54:49 +0000428 """Handles one command line during command list definition."""
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000429 cmd, arg, line = self.parseline(line)
Georg Brandl44f8bf92010-07-30 08:54:49 +0000430 if not cmd:
431 return
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000432 if cmd == 'silent':
433 self.commands_silent[self.commands_bnum] = True
434 return # continue to handle other cmd def in the cmd list
435 elif cmd == 'end':
436 self.cmdqueue = []
437 return 1 # end of cmd list
438 cmdlist = self.commands[self.commands_bnum]
Georg Brandl44f8bf92010-07-30 08:54:49 +0000439 if arg:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000440 cmdlist.append(cmd+' '+arg)
441 else:
442 cmdlist.append(cmd)
443 # Determine if we must stop
444 try:
445 func = getattr(self, 'do_' + cmd)
446 except AttributeError:
447 func = self.default
Georg Brandl3078df02009-05-05 09:11:31 +0000448 # one of the resuming commands
449 if func.__name__ in self.commands_resuming:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000450 self.commands_doprompt[self.commands_bnum] = False
451 self.cmdqueue = []
452 return 1
453 return
454
Georg Brandl0d089622010-07-30 16:00:46 +0000455 # interface abstraction functions
456
457 def message(self, msg):
458 print(msg, file=self.stdout)
459
460 def error(self, msg):
461 print('***', msg, file=self.stdout)
462
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100463 # Generic completion functions. Individual complete_foo methods can be
464 # assigned below to one of these functions.
465
466 def _complete_location(self, text, line, begidx, endidx):
467 # Complete a file/module/function location for break/tbreak/clear.
468 if line.strip().endswith((':', ',')):
469 # Here comes a line number or a condition which we can't complete.
470 return []
471 # First, try to find matching functions (i.e. expressions).
472 try:
473 ret = self._complete_expression(text, line, begidx, endidx)
474 except Exception:
475 ret = []
476 # Then, try to complete file names as well.
Serhiy Storchaka93558682020-06-20 11:10:31 +0300477 globs = glob.glob(glob.escape(text) + '*')
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100478 for fn in globs:
479 if os.path.isdir(fn):
480 ret.append(fn + '/')
481 elif os.path.isfile(fn) and fn.lower().endswith(('.py', '.pyw')):
482 ret.append(fn + ':')
483 return ret
484
485 def _complete_bpnumber(self, text, line, begidx, endidx):
486 # Complete a breakpoint number. (This would be more helpful if we could
487 # display additional info along with the completions, such as file/line
488 # of the breakpoint.)
489 return [str(i) for i, bp in enumerate(bdb.Breakpoint.bpbynumber)
490 if bp is not None and str(i).startswith(text)]
491
492 def _complete_expression(self, text, line, begidx, endidx):
493 # Complete an arbitrary expression.
494 if not self.curframe:
495 return []
496 # Collect globals and locals. It is usually not really sensible to also
497 # complete builtins, and they clutter the namespace quite heavily, so we
498 # leave them out.
Serhiy Storchakada084702019-03-27 08:02:28 +0200499 ns = {**self.curframe.f_globals, **self.curframe_locals}
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100500 if '.' in text:
501 # Walk an attribute chain up to the last part, similar to what
502 # rlcompleter does. This will bail if any of the parts are not
503 # simple attribute access, which is what we want.
504 dotted = text.split('.')
505 try:
506 obj = ns[dotted[0]]
507 for part in dotted[1:-1]:
508 obj = getattr(obj, part)
509 except (KeyError, AttributeError):
510 return []
511 prefix = '.'.join(dotted[:-1]) + '.'
512 return [prefix + n for n in dir(obj) if n.startswith(dotted[-1])]
513 else:
514 # Complete a simple name.
515 return [n for n in ns.keys() if n.startswith(text)]
516
Tim Peters2344fae2001-01-15 00:50:52 +0000517 # Command definitions, called by cmdloop()
518 # The argument is the remaining string on the command line
519 # Return true to exit from the command loop
520
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000521 def do_commands(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000522 """commands [bpnumber]
523 (com) ...
524 (com) end
525 (Pdb)
Georg Brandl3078df02009-05-05 09:11:31 +0000526
Georg Brandl0d089622010-07-30 16:00:46 +0000527 Specify a list of commands for breakpoint number bpnumber.
528 The commands themselves are entered on the following lines.
529 Type a line containing just 'end' to terminate the commands.
530 The commands are executed when the breakpoint is hit.
531
532 To remove all commands from a breakpoint, type commands and
533 follow it immediately with end; that is, give no commands.
534
535 With no bpnumber argument, commands refers to the last
536 breakpoint set.
537
538 You can use breakpoint commands to start your program up
539 again. Simply use the continue command, or step, or any other
540 command that resumes execution.
541
542 Specifying any command resuming execution (currently continue,
543 step, next, return, jump, quit and their abbreviations)
544 terminates the command list (as if that command was
545 immediately followed by end). This is because any time you
546 resume execution (even with a simple next or step), you may
547 encounter another breakpoint -- which could have its own
548 command list, leading to ambiguities about which list to
549 execute.
550
551 If you use the 'silent' command in the command list, the usual
552 message about stopping at a breakpoint is not printed. This
553 may be desirable for breakpoints that are to print a specific
554 message and then continue. If none of the other commands
555 print anything, you will see no sign that the breakpoint was
556 reached.
557 """
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000558 if not arg:
Georg Brandl7410dd12010-07-30 12:01:20 +0000559 bnum = len(bdb.Breakpoint.bpbynumber) - 1
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000560 else:
561 try:
562 bnum = int(arg)
563 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000564 self.error("Usage: commands [bnum]\n ...\n end")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000565 return
566 self.commands_bnum = bnum
Georg Brandlb90ffd82010-07-30 22:20:16 +0000567 # Save old definitions for the case of a keyboard interrupt.
568 if bnum in self.commands:
569 old_command_defs = (self.commands[bnum],
570 self.commands_doprompt[bnum],
571 self.commands_silent[bnum])
572 else:
573 old_command_defs = None
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000574 self.commands[bnum] = []
575 self.commands_doprompt[bnum] = True
576 self.commands_silent[bnum] = False
Georg Brandlb90ffd82010-07-30 22:20:16 +0000577
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000578 prompt_back = self.prompt
579 self.prompt = '(com) '
580 self.commands_defining = True
Georg Brandl44f8bf92010-07-30 08:54:49 +0000581 try:
582 self.cmdloop()
Georg Brandlb90ffd82010-07-30 22:20:16 +0000583 except KeyboardInterrupt:
584 # Restore old definitions.
585 if old_command_defs:
586 self.commands[bnum] = old_command_defs[0]
587 self.commands_doprompt[bnum] = old_command_defs[1]
588 self.commands_silent[bnum] = old_command_defs[2]
589 else:
590 del self.commands[bnum]
591 del self.commands_doprompt[bnum]
592 del self.commands_silent[bnum]
593 self.error('command definition aborted, old commands restored')
Georg Brandl44f8bf92010-07-30 08:54:49 +0000594 finally:
595 self.commands_defining = False
596 self.prompt = prompt_back
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000597
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100598 complete_commands = _complete_bpnumber
599
Tim Peters2344fae2001-01-15 00:50:52 +0000600 def do_break(self, arg, temporary = 0):
Georg Brandl0d089622010-07-30 16:00:46 +0000601 """b(reak) [ ([filename:]lineno | function) [, condition] ]
602 Without argument, list all breaks.
603
604 With a line number argument, set a break at this line in the
605 current file. With a function name, set a break at the first
606 executable line of that function. If a second argument is
607 present, it is a string specifying an expression which must
608 evaluate to true before the breakpoint is honored.
609
610 The line number may be prefixed with a filename and a colon,
611 to specify a breakpoint in another file (probably one that
612 hasn't been loaded yet). The file is searched for on
613 sys.path; the .py suffix may be omitted.
614 """
Tim Peters2344fae2001-01-15 00:50:52 +0000615 if not arg:
616 if self.breaks: # There's at least one
Georg Brandl0d089622010-07-30 16:00:46 +0000617 self.message("Num Type Disp Enb Where")
Tim Peters2344fae2001-01-15 00:50:52 +0000618 for bp in bdb.Breakpoint.bpbynumber:
619 if bp:
Georg Brandl0d089622010-07-30 16:00:46 +0000620 self.message(bp.bpformat())
Tim Peters2344fae2001-01-15 00:50:52 +0000621 return
622 # parse arguments; comma has lowest precedence
623 # and cannot occur in filename
624 filename = None
625 lineno = None
626 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000627 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000628 if comma > 0:
629 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000630 cond = arg[comma+1:].lstrip()
631 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000632 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000633 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000634 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000635 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000636 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000637 f = self.lookupmodule(filename)
638 if not f:
Georg Brandl0d089622010-07-30 16:00:46 +0000639 self.error('%r not found from sys.path' % filename)
Tim Peters2344fae2001-01-15 00:50:52 +0000640 return
641 else:
642 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000643 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000644 try:
645 lineno = int(arg)
Georg Brandlf93390a2010-10-14 07:17:44 +0000646 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000647 self.error('Bad lineno: %s' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000648 return
649 else:
650 # no colon; can be lineno or function
651 try:
652 lineno = int(arg)
653 except ValueError:
654 try:
655 func = eval(arg,
656 self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +0000657 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000658 except:
659 func = arg
660 try:
Christian Heimesff737952007-11-27 10:40:20 +0000661 if hasattr(func, '__func__'):
662 func = func.__func__
Neal Norwitz221085d2007-02-25 20:55:47 +0000663 code = func.__code__
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000664 #use co_name to identify the bkpt (function names
665 #could be aliased, but co_name is invariant)
666 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000667 lineno = code.co_firstlineno
668 filename = code.co_filename
669 except:
670 # last thing to try
671 (ok, filename, ln) = self.lineinfo(arg)
672 if not ok:
Georg Brandl0d089622010-07-30 16:00:46 +0000673 self.error('The specified object %r is not a function '
674 'or was not found along sys.path.' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000675 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000676 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000677 lineno = int(ln)
678 if not filename:
679 filename = self.defaultFile()
680 # Check for reasonable breakpoint
681 line = self.checkline(filename, lineno)
682 if line:
683 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000684 err = self.set_break(filename, line, temporary, cond, funcname)
Georg Brandl0d089622010-07-30 16:00:46 +0000685 if err:
Berker Peksagad5ffd42014-07-12 18:24:32 +0300686 self.error(err)
Tim Peters2344fae2001-01-15 00:50:52 +0000687 else:
688 bp = self.get_breaks(filename, line)[-1]
Georg Brandl0d089622010-07-30 16:00:46 +0000689 self.message("Breakpoint %d at %s:%d" %
690 (bp.number, bp.file, bp.line))
Tim Peters2344fae2001-01-15 00:50:52 +0000691
692 # To be overridden in derived debuggers
693 def defaultFile(self):
694 """Produce a reasonable default."""
695 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000696 if filename == '<string>' and self.mainpyfile:
697 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000698 return filename
699
700 do_b = do_break
701
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100702 complete_break = _complete_location
703 complete_b = _complete_location
704
Tim Peters2344fae2001-01-15 00:50:52 +0000705 def do_tbreak(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000706 """tbreak [ ([filename:]lineno | function) [, condition] ]
707 Same arguments as break, but sets a temporary breakpoint: it
708 is automatically deleted when first hit.
709 """
Tim Peters2344fae2001-01-15 00:50:52 +0000710 self.do_break(arg, 1)
711
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100712 complete_tbreak = _complete_location
713
Tim Peters2344fae2001-01-15 00:50:52 +0000714 def lineinfo(self, identifier):
715 failed = (None, None, None)
716 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000717 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000718 if len(idstring) == 1:
719 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000720 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000721 elif len(idstring) == 3:
722 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000723 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000724 else:
725 return failed
726 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000727 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000728 # Protection for derived debuggers
729 if parts[0] == 'self':
730 del parts[0]
731 if len(parts) == 0:
732 return failed
733 # Best first guess at file to look at
734 fname = self.defaultFile()
735 if len(parts) == 1:
736 item = parts[0]
737 else:
738 # More than one part.
739 # First is module, second is method/class
740 f = self.lookupmodule(parts[0])
741 if f:
742 fname = f
743 item = parts[1]
744 answer = find_function(item, fname)
745 return answer or failed
746
747 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000748 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000749
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000750 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
751 line or EOF). Warning: testing is not comprehensive.
752 """
Georg Brandl1e30bd32010-07-30 07:21:26 +0000753 # this method should be callable before starting debugging, so default
754 # to "no globals" if there is no current frame
Miss Islington (bot)c90ed8e2021-05-11 16:48:05 -0700755 frame = getattr(self, 'curframe', None)
756 globs = frame.f_globals if frame else None
Georg Brandl1e30bd32010-07-30 07:21:26 +0000757 line = linecache.getline(filename, lineno, globs)
Tim Peters2344fae2001-01-15 00:50:52 +0000758 if not line:
Georg Brandl0d089622010-07-30 16:00:46 +0000759 self.message('End of file')
Tim Peters2344fae2001-01-15 00:50:52 +0000760 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000761 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000762 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000763 if (not line or (line[0] == '#') or
764 (line[:3] == '"""') or line[:3] == "'''"):
Georg Brandl0d089622010-07-30 16:00:46 +0000765 self.error('Blank or comment')
Tim Peters2344fae2001-01-15 00:50:52 +0000766 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000767 return lineno
768
769 def do_enable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000770 """enable bpnumber [bpnumber ...]
771 Enables the breakpoints given as a space separated list of
772 breakpoint numbers.
773 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000774 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000775 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000776 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000777 bp = self.get_bpbynumber(i)
778 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000779 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000780 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000781 bp.enable()
Georg Brandl0d089622010-07-30 16:00:46 +0000782 self.message('Enabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000783
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100784 complete_enable = _complete_bpnumber
785
Tim Peters2344fae2001-01-15 00:50:52 +0000786 def do_disable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000787 """disable bpnumber [bpnumber ...]
788 Disables the breakpoints given as a space separated list of
789 breakpoint numbers. Disabling a breakpoint means it cannot
790 cause the program to stop execution, but unlike clearing a
791 breakpoint, it remains in the list of breakpoints and can be
792 (re-)enabled.
793 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000794 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000795 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000796 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000797 bp = self.get_bpbynumber(i)
798 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000799 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000800 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000801 bp.disable()
Georg Brandl0d089622010-07-30 16:00:46 +0000802 self.message('Disabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000803
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100804 complete_disable = _complete_bpnumber
805
Tim Peters2344fae2001-01-15 00:50:52 +0000806 def do_condition(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000807 """condition bpnumber [condition]
808 Set a new condition for the breakpoint, an expression which
809 must evaluate to true before the breakpoint is honored. If
810 condition is absent, any existing condition is removed; i.e.,
811 the breakpoint is made unconditional.
812 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000813 args = arg.split(' ', 1)
Thomas Woutersb2137042007-02-01 18:02:27 +0000814 try:
Tim Peters2344fae2001-01-15 00:50:52 +0000815 cond = args[1]
Georg Brandl7410dd12010-07-30 12:01:20 +0000816 except IndexError:
Tim Peters2344fae2001-01-15 00:50:52 +0000817 cond = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000818 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000819 bp = self.get_bpbynumber(args[0].strip())
Georg Brandl0079ffc2013-10-14 16:08:15 +0200820 except IndexError:
821 self.error('Breakpoint number expected')
Georg Brandl7410dd12010-07-30 12:01:20 +0000822 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000823 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000824 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000825 bp.cond = cond
826 if not cond:
Georg Brandl0d089622010-07-30 16:00:46 +0000827 self.message('Breakpoint %d is now unconditional.' % bp.number)
Georg Brandl7410dd12010-07-30 12:01:20 +0000828 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000829 self.message('New condition set for breakpoint %d.' % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000830
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100831 complete_condition = _complete_bpnumber
832
Georg Brandl7410dd12010-07-30 12:01:20 +0000833 def do_ignore(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000834 """ignore bpnumber [count]
835 Set the ignore count for the given breakpoint number. If
836 count is omitted, the ignore count is set to 0. A breakpoint
837 becomes active when the ignore count is zero. When non-zero,
838 the count is decremented each time the breakpoint is reached
839 and the breakpoint is not disabled and any associated
840 condition evaluates to true.
841 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000842 args = arg.split()
Thomas Woutersb2137042007-02-01 18:02:27 +0000843 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000844 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000845 except:
846 count = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +0000847 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000848 bp = self.get_bpbynumber(args[0].strip())
Georg Brandl0079ffc2013-10-14 16:08:15 +0200849 except IndexError:
850 self.error('Breakpoint number expected')
Georg Brandl7410dd12010-07-30 12:01:20 +0000851 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000852 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000853 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000854 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000855 if count > 0:
Guido van Rossum08454592002-07-12 13:10:53 +0000856 if count > 1:
Georg Brandl0d089622010-07-30 16:00:46 +0000857 countstr = '%d crossings' % count
Tim Peters2344fae2001-01-15 00:50:52 +0000858 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000859 countstr = '1 crossing'
860 self.message('Will ignore next %s of breakpoint %d.' %
861 (countstr, bp.number))
Tim Peters2344fae2001-01-15 00:50:52 +0000862 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000863 self.message('Will stop next time breakpoint %d is reached.'
864 % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000865
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100866 complete_ignore = _complete_bpnumber
867
Tim Peters2344fae2001-01-15 00:50:52 +0000868 def do_clear(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000869 """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]]
870 With a space separated list of breakpoint numbers, clear
871 those breakpoints. Without argument, clear all breaks (but
872 first ask confirmation). With a filename:lineno argument,
873 clear all breaks at that line in that file.
874 """
Tim Peters2344fae2001-01-15 00:50:52 +0000875 if not arg:
876 try:
Guido van Rossumc5b6ab02007-05-27 09:19:52 +0000877 reply = input('Clear all breaks? ')
Tim Peters2344fae2001-01-15 00:50:52 +0000878 except EOFError:
879 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000880 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000881 if reply in ('y', 'yes'):
Georg Brandl7410dd12010-07-30 12:01:20 +0000882 bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp]
Tim Peters2344fae2001-01-15 00:50:52 +0000883 self.clear_all_breaks()
Georg Brandl7410dd12010-07-30 12:01:20 +0000884 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000885 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000886 return
887 if ':' in arg:
888 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000889 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000890 filename = arg[:i]
891 arg = arg[i+1:]
892 try:
893 lineno = int(arg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000894 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000895 err = "Invalid line number (%s)" % arg
896 else:
Georg Brandl7410dd12010-07-30 12:01:20 +0000897 bplist = self.get_breaks(filename, lineno)
Tim Peters2344fae2001-01-15 00:50:52 +0000898 err = self.clear_break(filename, lineno)
Georg Brandl7410dd12010-07-30 12:01:20 +0000899 if err:
Georg Brandl0d089622010-07-30 16:00:46 +0000900 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000901 else:
902 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000903 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000904 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000905 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000906 for i in numberlist:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000907 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000908 bp = self.get_bpbynumber(i)
909 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000910 self.error(err)
Tim Peters2344fae2001-01-15 00:50:52 +0000911 else:
Senthil Kumaran6f107042010-11-29 11:54:17 +0000912 self.clear_bpbynumber(i)
Georg Brandl0d089622010-07-30 16:00:46 +0000913 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000914 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
915
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100916 complete_clear = _complete_location
917 complete_cl = _complete_location
918
Tim Peters2344fae2001-01-15 00:50:52 +0000919 def do_where(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000920 """w(here)
921 Print a stack trace, with the most recent frame at the bottom.
922 An arrow indicates the "current frame", which determines the
923 context of most commands. 'bt' is an alias for this command.
924 """
Tim Peters2344fae2001-01-15 00:50:52 +0000925 self.print_stack_trace()
926 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000927 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000928
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000929 def _select_frame(self, number):
930 assert 0 <= number < len(self.stack)
931 self.curindex = number
932 self.curframe = self.stack[self.curindex][0]
933 self.curframe_locals = self.curframe.f_locals
934 self.print_stack_entry(self.stack[self.curindex])
935 self.lineno = None
936
Tim Peters2344fae2001-01-15 00:50:52 +0000937 def do_up(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000938 """u(p) [count]
939 Move the current frame count (default one) levels up in the
940 stack trace (to an older frame).
941 """
Tim Peters2344fae2001-01-15 00:50:52 +0000942 if self.curindex == 0:
Georg Brandl0d089622010-07-30 16:00:46 +0000943 self.error('Oldest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000944 return
945 try:
946 count = int(arg or 1)
947 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000948 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000949 return
950 if count < 0:
951 newframe = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000952 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000953 newframe = max(0, self.curindex - count)
954 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000955 do_u = do_up
956
957 def do_down(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000958 """d(own) [count]
959 Move the current frame count (default one) levels down in the
960 stack trace (to a newer frame).
961 """
Tim Peters2344fae2001-01-15 00:50:52 +0000962 if self.curindex + 1 == len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +0000963 self.error('Newest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000964 return
965 try:
966 count = int(arg or 1)
967 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000968 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000969 return
970 if count < 0:
971 newframe = len(self.stack) - 1
Tim Peters2344fae2001-01-15 00:50:52 +0000972 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000973 newframe = min(len(self.stack) - 1, self.curindex + count)
974 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000975 do_d = do_down
976
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000977 def do_until(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000978 """unt(il) [lineno]
979 Without argument, continue execution until the line with a
980 number greater than the current one is reached. With a line
981 number, continue execution until a line with a number greater
982 or equal to that is reached. In both cases, also stop when
983 the current frame returns.
984 """
Georg Brandl2dfec552010-07-30 08:43:32 +0000985 if arg:
986 try:
987 lineno = int(arg)
988 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000989 self.error('Error in argument: %r' % arg)
Georg Brandl2dfec552010-07-30 08:43:32 +0000990 return
991 if lineno <= self.curframe.f_lineno:
Georg Brandl0d089622010-07-30 16:00:46 +0000992 self.error('"until" line number is smaller than current '
993 'line number')
Georg Brandl2dfec552010-07-30 08:43:32 +0000994 return
995 else:
996 lineno = None
997 self.set_until(self.curframe, lineno)
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000998 return 1
999 do_unt = do_until
1000
Tim Peters2344fae2001-01-15 00:50:52 +00001001 def do_step(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001002 """s(tep)
1003 Execute the current line, stop at the first possible occasion
1004 (either in a function that is called or in the current
1005 function).
1006 """
Tim Peters2344fae2001-01-15 00:50:52 +00001007 self.set_step()
1008 return 1
1009 do_s = do_step
1010
1011 def do_next(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001012 """n(ext)
1013 Continue execution until the next line in the current function
1014 is reached or it returns.
1015 """
Tim Peters2344fae2001-01-15 00:50:52 +00001016 self.set_next(self.curframe)
1017 return 1
1018 do_n = do_next
1019
Guido van Rossumd8faa362007-04-27 19:54:29 +00001020 def do_run(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001021 """run [args...]
1022 Restart the debugged python program. If a string is supplied
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001023 it is split with "shlex", and the result is used as the new
Georg Brandl0d089622010-07-30 16:00:46 +00001024 sys.argv. History, breakpoints, actions and debugger options
1025 are preserved. "restart" is an alias for "run".
1026 """
Guido van Rossumd8faa362007-04-27 19:54:29 +00001027 if arg:
1028 import shlex
1029 argv0 = sys.argv[0:1]
1030 sys.argv = shlex.split(arg)
1031 sys.argv[:0] = argv0
Georg Brandl0d089622010-07-30 16:00:46 +00001032 # this is caught in the main debugger loop
Guido van Rossumd8faa362007-04-27 19:54:29 +00001033 raise Restart
1034
1035 do_restart = do_run
1036
Tim Peters2344fae2001-01-15 00:50:52 +00001037 def do_return(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001038 """r(eturn)
1039 Continue execution until the current function returns.
1040 """
Tim Peters2344fae2001-01-15 00:50:52 +00001041 self.set_return(self.curframe)
1042 return 1
1043 do_r = do_return
1044
1045 def do_continue(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001046 """c(ont(inue))
1047 Continue execution, only stop when a breakpoint is encountered.
1048 """
Georg Brandl44f2b642010-12-04 16:00:47 +00001049 if not self.nosigint:
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001050 try:
Xavier de Gaye10e54ae2016-10-12 20:13:24 +02001051 Pdb._previous_sigint_handler = \
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001052 signal.signal(signal.SIGINT, self.sigint_handler)
1053 except ValueError:
1054 # ValueError happens when do_continue() is invoked from
1055 # a non-main thread in which case we just continue without
1056 # SIGINT set. Would printing a message here (once) make
1057 # sense?
1058 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001059 self.set_continue()
1060 return 1
1061 do_c = do_cont = do_continue
1062
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001063 def do_jump(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001064 """j(ump) lineno
1065 Set the next line that will be executed. Only available in
1066 the bottom-most frame. This lets you jump back and execute
1067 code again, or jump forward to skip code that you don't want
1068 to run.
1069
1070 It should be noted that not all jumps are allowed -- for
1071 instance it is not possible to jump into the middle of a
1072 for loop or out of a finally clause.
1073 """
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001074 if self.curindex + 1 != len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +00001075 self.error('You can only jump within the bottom frame')
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001076 return
1077 try:
1078 arg = int(arg)
1079 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +00001080 self.error("The 'jump' command requires a line number")
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001081 else:
1082 try:
1083 # Do the jump, fix up our copy of the stack, and display the
1084 # new position
1085 self.curframe.f_lineno = arg
1086 self.stack[self.curindex] = self.stack[self.curindex][0], arg
1087 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumb940e112007-01-10 16:19:56 +00001088 except ValueError as e:
Georg Brandl0d089622010-07-30 16:00:46 +00001089 self.error('Jump failed: %s' % e)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001090 do_j = do_jump
1091
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001092 def do_debug(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001093 """debug code
1094 Enter a recursive debugger that steps through the code
1095 argument (which is an arbitrary expression or statement to be
1096 executed in the current environment).
1097 """
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001098 sys.settrace(None)
1099 globals = self.curframe.f_globals
Benjamin Petersond23f8222009-04-05 19:13:16 +00001100 locals = self.curframe_locals
Guido van Rossum7736b5b2008-01-15 21:44:53 +00001101 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +00001102 p.prompt = "(%s) " % self.prompt.strip()
Georg Brandl0d089622010-07-30 16:00:46 +00001103 self.message("ENTERING RECURSIVE DEBUGGER")
Daniel Hahler3e936432019-03-12 04:29:04 +01001104 try:
1105 sys.call_tracing(p.run, (arg, globals, locals))
1106 except Exception:
1107 exc_info = sys.exc_info()[:2]
1108 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Georg Brandl0d089622010-07-30 16:00:46 +00001109 self.message("LEAVING RECURSIVE DEBUGGER")
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001110 sys.settrace(self.trace_dispatch)
1111 self.lastcmd = p.lastcmd
1112
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001113 complete_debug = _complete_expression
1114
Tim Peters2344fae2001-01-15 00:50:52 +00001115 def do_quit(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001116 """q(uit)\nexit
1117 Quit from the debugger. The program being executed is aborted.
1118 """
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001119 self._user_requested_quit = True
Tim Peters2344fae2001-01-15 00:50:52 +00001120 self.set_quit()
1121 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001122
Tim Peters2344fae2001-01-15 00:50:52 +00001123 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +00001124 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +00001125
Guido van Rossumeef26072003-01-13 21:13:55 +00001126 def do_EOF(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001127 """EOF
1128 Handles the receipt of EOF as a command.
1129 """
1130 self.message('')
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001131 self._user_requested_quit = True
Guido van Rossumeef26072003-01-13 21:13:55 +00001132 self.set_quit()
1133 return 1
1134
Tim Peters2344fae2001-01-15 00:50:52 +00001135 def do_args(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001136 """a(rgs)
1137 Print the argument list of the current function.
1138 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001139 co = self.curframe.f_code
1140 dict = self.curframe_locals
Pablo Galindocd74e662019-06-01 18:08:04 +01001141 n = co.co_argcount + co.co_kwonlyargcount
Rémi Lapeyrebf457c72019-05-21 00:17:30 +02001142 if co.co_flags & inspect.CO_VARARGS: n = n+1
1143 if co.co_flags & inspect.CO_VARKEYWORDS: n = n+1
Tim Peters2344fae2001-01-15 00:50:52 +00001144 for i in range(n):
1145 name = co.co_varnames[i]
Georg Brandl0d089622010-07-30 16:00:46 +00001146 if name in dict:
1147 self.message('%s = %r' % (name, dict[name]))
1148 else:
1149 self.message('%s = *** undefined ***' % (name,))
Tim Peters2344fae2001-01-15 00:50:52 +00001150 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +00001151
Tim Peters2344fae2001-01-15 00:50:52 +00001152 def do_retval(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001153 """retval
1154 Print the return value for the last return of a function.
1155 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001156 if '__return__' in self.curframe_locals:
Georg Brandl0d089622010-07-30 16:00:46 +00001157 self.message(repr(self.curframe_locals['__return__']))
Tim Peters2344fae2001-01-15 00:50:52 +00001158 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001159 self.error('Not yet returned!')
Tim Peters2344fae2001-01-15 00:50:52 +00001160 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +00001161
Barry Warsaw210bd202002-11-05 22:40:20 +00001162 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +00001163 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +00001164 return eval(arg, self.curframe.f_globals, self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +00001165 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001166 exc_info = sys.exc_info()[:2]
1167 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Barry Warsaw210bd202002-11-05 22:40:20 +00001168 raise
Guido van Rossum2424f851998-09-11 22:50:09 +00001169
Georg Brandlcbc79c72010-12-04 16:21:42 +00001170 def _getval_except(self, arg, frame=None):
1171 try:
1172 if frame is None:
1173 return eval(arg, self.curframe.f_globals, self.curframe_locals)
1174 else:
1175 return eval(arg, frame.f_globals, frame.f_locals)
1176 except:
1177 exc_info = sys.exc_info()[:2]
1178 err = traceback.format_exception_only(*exc_info)[-1].strip()
1179 return _rstr('** raised %s **' % err)
1180
Barry Warsaw210bd202002-11-05 22:40:20 +00001181 def do_p(self, arg):
R David Murray78d692f2013-10-10 17:23:26 -04001182 """p expression
Georg Brandl0d089622010-07-30 16:00:46 +00001183 Print the value of the expression.
1184 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001185 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001186 self.message(repr(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001187 except:
1188 pass
1189
1190 def do_pp(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001191 """pp expression
1192 Pretty-print the value of the expression.
1193 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001194 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001195 self.message(pprint.pformat(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001196 except:
1197 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001198
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001199 complete_print = _complete_expression
1200 complete_p = _complete_expression
1201 complete_pp = _complete_expression
1202
Tim Peters2344fae2001-01-15 00:50:52 +00001203 def do_list(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001204 """l(ist) [first [,last] | .]
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001205
1206 List source code for the current file. Without arguments,
1207 list 11 lines around the current line or continue the previous
1208 listing. With . as argument, list 11 lines around the current
1209 line. With one argument, list 11 lines starting at that line.
1210 With two arguments, list the given range; if the second
1211 argument is less than the first, it is a count.
1212
1213 The current line in the current frame is indicated by "->".
1214 If an exception is being debugged, the line where the
1215 exception was originally raised or propagated is indicated by
1216 ">>", if it differs from the current line.
Georg Brandl0d089622010-07-30 16:00:46 +00001217 """
Tim Peters2344fae2001-01-15 00:50:52 +00001218 self.lastcmd = 'list'
1219 last = None
Georg Brandla91a94b2010-07-30 07:14:01 +00001220 if arg and arg != '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001221 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001222 if ',' in arg:
1223 first, last = arg.split(',')
1224 first = int(first.strip())
1225 last = int(last.strip())
Tim Peters2344fae2001-01-15 00:50:52 +00001226 if last < first:
Georg Brandl0d089622010-07-30 16:00:46 +00001227 # assume it's a count
Tim Peters2344fae2001-01-15 00:50:52 +00001228 last = first + last
1229 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001230 first = int(arg.strip())
1231 first = max(1, first - 5)
1232 except ValueError:
1233 self.error('Error in argument: %r' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001234 return
Georg Brandla91a94b2010-07-30 07:14:01 +00001235 elif self.lineno is None or arg == '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001236 first = max(1, self.curframe.f_lineno - 5)
1237 else:
1238 first = self.lineno + 1
1239 if last is None:
1240 last = first + 10
1241 filename = self.curframe.f_code.co_filename
1242 breaklist = self.get_file_breaks(filename)
1243 try:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001244 lines = linecache.getlines(filename, self.curframe.f_globals)
1245 self._print_lines(lines[first-1:last], first, breaklist,
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001246 self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001247 self.lineno = min(last, len(lines))
1248 if len(lines) < last:
1249 self.message('[EOF]')
Tim Peters2344fae2001-01-15 00:50:52 +00001250 except KeyboardInterrupt:
1251 pass
1252 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +00001253
Georg Brandle59ca2a2010-07-30 17:04:28 +00001254 def do_longlist(self, arg):
1255 """longlist | ll
1256 List the whole source code for the current function or frame.
1257 """
1258 filename = self.curframe.f_code.co_filename
1259 breaklist = self.get_file_breaks(filename)
1260 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001261 lines, lineno = getsourcelines(self.curframe)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001262 except OSError as err:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001263 self.error(err)
1264 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001265 self._print_lines(lines, lineno, breaklist, self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001266 do_ll = do_longlist
1267
1268 def do_source(self, arg):
1269 """source expression
1270 Try to get source code for the given object and display it.
1271 """
1272 try:
1273 obj = self._getval(arg)
1274 except:
1275 return
1276 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001277 lines, lineno = getsourcelines(obj)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001278 except (OSError, TypeError) as err:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001279 self.error(err)
1280 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001281 self._print_lines(lines, lineno)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001282
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001283 complete_source = _complete_expression
1284
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001285 def _print_lines(self, lines, start, breaks=(), frame=None):
Georg Brandle59ca2a2010-07-30 17:04:28 +00001286 """Print a range of lines."""
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001287 if frame:
1288 current_lineno = frame.f_lineno
1289 exc_lineno = self.tb_lineno.get(frame, -1)
1290 else:
1291 current_lineno = exc_lineno = -1
Georg Brandle59ca2a2010-07-30 17:04:28 +00001292 for lineno, line in enumerate(lines, start):
1293 s = str(lineno).rjust(3)
1294 if len(s) < 4:
1295 s += ' '
1296 if lineno in breaks:
1297 s += 'B'
1298 else:
1299 s += ' '
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001300 if lineno == current_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001301 s += '->'
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001302 elif lineno == exc_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001303 s += '>>'
1304 self.message(s + '\t' + line.rstrip())
1305
Tim Peters2344fae2001-01-15 00:50:52 +00001306 def do_whatis(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001307 """whatis arg
1308 Print the type of the argument.
1309 """
Tim Peters2344fae2001-01-15 00:50:52 +00001310 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001311 value = self._getval(arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001312 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001313 # _getval() already printed the error
Tim Peters2344fae2001-01-15 00:50:52 +00001314 return
1315 code = None
Tim Peters2344fae2001-01-15 00:50:52 +00001316 # Is it an instance method?
Georg Brandl0d089622010-07-30 16:00:46 +00001317 try:
1318 code = value.__func__.__code__
1319 except Exception:
1320 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001321 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001322 self.message('Method %s' % code.co_name)
1323 return
Irit Katriel022bc752020-08-27 01:51:12 +01001324 # Is it a function?
1325 try:
1326 code = value.__code__
1327 except Exception:
1328 pass
1329 if code:
1330 self.message('Function %s' % code.co_name)
1331 return
Georg Brandl0d089622010-07-30 16:00:46 +00001332 # Is it a class?
1333 if value.__class__ is type:
Serhiy Storchaka521e5862014-07-22 15:00:37 +03001334 self.message('Class %s.%s' % (value.__module__, value.__qualname__))
Tim Peters2344fae2001-01-15 00:50:52 +00001335 return
1336 # None of the above...
Georg Brandl0d089622010-07-30 16:00:46 +00001337 self.message(type(value))
Guido van Rossum8e2ec561993-07-29 09:37:38 +00001338
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001339 complete_whatis = _complete_expression
1340
Georg Brandlcbc79c72010-12-04 16:21:42 +00001341 def do_display(self, arg):
1342 """display [expression]
1343
1344 Display the value of the expression if it changed, each time execution
1345 stops in the current frame.
1346
1347 Without expression, list all display expressions for the current frame.
1348 """
1349 if not arg:
1350 self.message('Currently displaying:')
1351 for item in self.displaying.get(self.curframe, {}).items():
1352 self.message('%s: %r' % item)
1353 else:
1354 val = self._getval_except(arg)
1355 self.displaying.setdefault(self.curframe, {})[arg] = val
1356 self.message('display %s: %r' % (arg, val))
1357
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001358 complete_display = _complete_expression
1359
Georg Brandlcbc79c72010-12-04 16:21:42 +00001360 def do_undisplay(self, arg):
1361 """undisplay [expression]
1362
1363 Do not display the expression any more in the current frame.
1364
1365 Without expression, clear all display expressions for the current frame.
1366 """
1367 if arg:
1368 try:
1369 del self.displaying.get(self.curframe, {})[arg]
1370 except KeyError:
1371 self.error('not displaying %s' % arg)
1372 else:
1373 self.displaying.pop(self.curframe, None)
1374
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001375 def complete_undisplay(self, text, line, begidx, endidx):
1376 return [e for e in self.displaying.get(self.curframe, {})
1377 if e.startswith(text)]
1378
Georg Brandl1acb7462010-12-04 11:20:26 +00001379 def do_interact(self, arg):
1380 """interact
1381
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001382 Start an interactive interpreter whose global namespace
Georg Brandl1acb7462010-12-04 11:20:26 +00001383 contains all the (global and local) names found in the current scope.
1384 """
Serhiy Storchakada084702019-03-27 08:02:28 +02001385 ns = {**self.curframe.f_globals, **self.curframe_locals}
Georg Brandl1acb7462010-12-04 11:20:26 +00001386 code.interact("*interactive*", local=ns)
1387
Tim Peters2344fae2001-01-15 00:50:52 +00001388 def do_alias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001389 """alias [name [command [parameter parameter ...] ]]
1390 Create an alias called 'name' that executes 'command'. The
1391 command must *not* be enclosed in quotes. Replaceable
1392 parameters can be indicated by %1, %2, and so on, while %* is
1393 replaced by all the parameters. If no command is given, the
1394 current alias for name is shown. If no name is given, all
1395 aliases are listed.
1396
1397 Aliases may be nested and can contain anything that can be
1398 legally typed at the pdb prompt. Note! You *can* override
1399 internal pdb commands with aliases! Those internal commands
1400 are then hidden until the alias is removed. Aliasing is
1401 recursively applied to the first word of the command line; all
1402 other words in the line are left alone.
1403
1404 As an example, here are two useful aliases (especially when
1405 placed in the .pdbrc file):
1406
1407 # Print instance variables (usage "pi classInst")
R David Murray78d692f2013-10-10 17:23:26 -04001408 alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])
Georg Brandl0d089622010-07-30 16:00:46 +00001409 # Print instance variables in self
1410 alias ps pi self
1411 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001412 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001413 if len(args) == 0:
Benjamin Petersonbe74a372009-09-11 21:17:13 +00001414 keys = sorted(self.aliases.keys())
Tim Peters2344fae2001-01-15 00:50:52 +00001415 for alias in keys:
Georg Brandl0d089622010-07-30 16:00:46 +00001416 self.message("%s = %s" % (alias, self.aliases[alias]))
Tim Peters2344fae2001-01-15 00:50:52 +00001417 return
Guido van Rossum08454592002-07-12 13:10:53 +00001418 if args[0] in self.aliases and len(args) == 1:
Georg Brandl0d089622010-07-30 16:00:46 +00001419 self.message("%s = %s" % (args[0], self.aliases[args[0]]))
Tim Peters2344fae2001-01-15 00:50:52 +00001420 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001421 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +00001422
Tim Peters2344fae2001-01-15 00:50:52 +00001423 def do_unalias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001424 """unalias name
1425 Delete the specified alias.
1426 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001427 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001428 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +00001429 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +00001430 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +00001431
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001432 def complete_unalias(self, text, line, begidx, endidx):
1433 return [a for a in self.aliases if a.startswith(text)]
1434
Georg Brandl0d089622010-07-30 16:00:46 +00001435 # List of all the commands making the program resume execution.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001436 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
1437 'do_quit', 'do_jump']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001438
Tim Peters2344fae2001-01-15 00:50:52 +00001439 # Print a traceback starting at the top stack frame.
1440 # The most recently entered frame is printed last;
1441 # this is different from dbx and gdb, but consistent with
1442 # the Python interpreter's stack trace.
1443 # It is also consistent with the up/down commands (which are
1444 # compatible with dbx and gdb: up moves towards 'main()'
1445 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +00001446
Tim Peters2344fae2001-01-15 00:50:52 +00001447 def print_stack_trace(self):
1448 try:
1449 for frame_lineno in self.stack:
1450 self.print_stack_entry(frame_lineno)
1451 except KeyboardInterrupt:
1452 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001453
Tim Peters2344fae2001-01-15 00:50:52 +00001454 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
1455 frame, lineno = frame_lineno
1456 if frame is self.curframe:
Georg Brandl0d089622010-07-30 16:00:46 +00001457 prefix = '> '
Tim Peters2344fae2001-01-15 00:50:52 +00001458 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001459 prefix = ' '
1460 self.message(prefix +
1461 self.format_stack_entry(frame_lineno, prompt_prefix))
Guido van Rossum2424f851998-09-11 22:50:09 +00001462
Georg Brandl0d089622010-07-30 16:00:46 +00001463 # Provide help
Guido van Rossum921c8241992-01-10 14:54:42 +00001464
Georg Brandl0d089622010-07-30 16:00:46 +00001465 def do_help(self, arg):
1466 """h(elp)
1467 Without argument, print the list of available commands.
1468 With a command name as argument, print help about that command.
1469 "help pdb" shows the full pdb documentation.
1470 "help exec" gives help on the ! command.
1471 """
1472 if not arg:
1473 return cmd.Cmd.do_help(self, arg)
1474 try:
1475 try:
1476 topic = getattr(self, 'help_' + arg)
1477 return topic()
1478 except AttributeError:
1479 command = getattr(self, 'do_' + arg)
1480 except AttributeError:
1481 self.error('No help for %r' % arg)
1482 else:
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001483 if sys.flags.optimize >= 2:
1484 self.error('No help for %r; please do not run Python with -OO '
1485 'if you need command help' % arg)
1486 return
Georg Brandl0d089622010-07-30 16:00:46 +00001487 self.message(command.__doc__.rstrip())
Guido van Rossum921c8241992-01-10 14:54:42 +00001488
Georg Brandl0d089622010-07-30 16:00:46 +00001489 do_h = do_help
Barry Warsaw210bd202002-11-05 22:40:20 +00001490
Tim Peters2344fae2001-01-15 00:50:52 +00001491 def help_exec(self):
Georg Brandl0d089622010-07-30 16:00:46 +00001492 """(!) statement
1493 Execute the (one-line) statement in the context of the current
1494 stack frame. The exclamation point can be omitted unless the
1495 first word of the statement resembles a debugger command. To
1496 assign to a global variable you must always prefix the command
1497 with a 'global' command, e.g.:
1498 (Pdb) global list_options; list_options = ['-l']
1499 (Pdb)
1500 """
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001501 self.message((self.help_exec.__doc__ or '').strip())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001502
Tim Peters2344fae2001-01-15 00:50:52 +00001503 def help_pdb(self):
1504 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001505
Georg Brandl0d089622010-07-30 16:00:46 +00001506 # other helper functions
1507
Tim Peters2344fae2001-01-15 00:50:52 +00001508 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001509 """Helper function for break/clear parsing -- may be overridden.
1510
1511 lookupmodule() translates (possibly incomplete) file or module name
1512 into an absolute file name.
1513 """
1514 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001515 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001516 f = os.path.join(sys.path[0], filename)
1517 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1518 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001519 root, ext = os.path.splitext(filename)
1520 if ext == '':
1521 filename = filename + '.py'
1522 if os.path.isabs(filename):
1523 return filename
1524 for dirname in sys.path:
1525 while os.path.islink(dirname):
1526 dirname = os.readlink(dirname)
1527 fullname = os.path.join(dirname, filename)
1528 if os.path.exists(fullname):
1529 return fullname
1530 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001531
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001532 def _runmodule(self, module_name):
1533 self._wait_for_mainpyfile = True
1534 self._user_requested_quit = False
1535 import runpy
1536 mod_name, mod_spec, code = runpy._get_module_details(module_name)
1537 self.mainpyfile = self.canonic(code.co_filename)
1538 import __main__
1539 __main__.__dict__.clear()
1540 __main__.__dict__.update({
1541 "__name__": "__main__",
1542 "__file__": self.mainpyfile,
Mario Corchero38bfa842018-02-03 06:40:11 +00001543 "__package__": mod_spec.parent,
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001544 "__loader__": mod_spec.loader,
1545 "__spec__": mod_spec,
1546 "__builtins__": __builtins__,
1547 })
1548 self.run(code)
1549
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001550 def _runscript(self, filename):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001551 # The script has to run in __main__ namespace (or imports from
1552 # __main__ will break).
1553 #
1554 # So we clear up the __main__ and set several special variables
1555 # (this gets rid of pdb's globals and cleans old variables on restarts).
1556 import __main__
1557 __main__.__dict__.clear()
1558 __main__.__dict__.update({"__name__" : "__main__",
1559 "__file__" : filename,
1560 "__builtins__": __builtins__,
1561 })
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001562
1563 # When bdb sets tracing, a number of call and line events happens
1564 # BEFORE debugger even reaches user's code (and the exact sequence of
1565 # events depends on python version). So we take special measures to
1566 # avoid stopping before we reach the main script (see user_line and
1567 # user_call for details).
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001568 self._wait_for_mainpyfile = True
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001569 self.mainpyfile = self.canonic(filename)
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001570 self._user_requested_quit = False
jsnkllnd5938812019-11-12 17:42:47 -05001571 with io.open_code(filename) as fp:
Georg Brandld07ac642009-08-13 07:50:57 +00001572 statement = "exec(compile(%r, %r, 'exec'))" % \
1573 (fp.read(), self.mainpyfile)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001574 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001575
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001576# Collect all command help into docstring, if not run with -OO
Georg Brandl0d089622010-07-30 16:00:46 +00001577
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001578if __doc__ is not None:
1579 # unfortunately we can't guess this order from the class definition
1580 _help_order = [
1581 'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable',
1582 'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until',
1583 'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist',
R David Murray78d692f2013-10-10 17:23:26 -04001584 'args', 'p', 'pp', 'whatis', 'source', 'display', 'undisplay',
Georg Brandlcbc79c72010-12-04 16:21:42 +00001585 'interact', 'alias', 'unalias', 'debug', 'quit',
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001586 ]
Georg Brandl0d089622010-07-30 16:00:46 +00001587
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001588 for _command in _help_order:
1589 __doc__ += getattr(Pdb, 'do_' + _command).__doc__.strip() + '\n\n'
1590 __doc__ += Pdb.help_exec.__doc__
Georg Brandl0d089622010-07-30 16:00:46 +00001591
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001592 del _help_order, _command
1593
Georg Brandl0d089622010-07-30 16:00:46 +00001594
Guido van Rossum35771131992-09-08 11:59:04 +00001595# Simplified interface
1596
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001597def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001598 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001599
1600def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001601 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001602
1603def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001604 # B/W compatibility
1605 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001606
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001607def runcall(*args, **kwds):
1608 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001609
Barry Warsaw35425d62017-09-22 12:29:42 -04001610def set_trace(*, header=None):
1611 pdb = Pdb()
1612 if header is not None:
1613 pdb.message(header)
1614 pdb.set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001615
1616# Post-Mortem interface
1617
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001618def post_mortem(t=None):
1619 # handling the default
1620 if t is None:
1621 # sys.exc_info() returns (type, value, traceback) if an exception is
1622 # being handled, otherwise it returns None
1623 t = sys.exc_info()[2]
Georg Brandl0d089622010-07-30 16:00:46 +00001624 if t is None:
1625 raise ValueError("A valid traceback must be passed if no "
1626 "exception is being handled")
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001627
Tim Peters2344fae2001-01-15 00:50:52 +00001628 p = Pdb()
1629 p.reset()
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001630 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001631
1632def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001633 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001634
1635
1636# Main program for testing
1637
Guido van Rossum23efba41992-01-27 16:58:47 +00001638TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001639
Guido van Rossum921c8241992-01-10 14:54:42 +00001640def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001641 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001642
1643# print help
1644def help():
Georg Brandl02053ee2010-07-18 10:11:03 +00001645 import pydoc
1646 pydoc.pager(__doc__)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001647
Georg Brandle0230912010-07-30 08:29:39 +00001648_usage = """\
Mario Corcherofcf8b4c2018-01-28 04:58:47 +00001649usage: pdb.py [-c command] ... [-m module | pyfile] [arg] ...
Georg Brandle0230912010-07-30 08:29:39 +00001650
Mario Corcherofcf8b4c2018-01-28 04:58:47 +00001651Debug the Python program given by pyfile. Alternatively,
1652an executable module or package to debug can be specified using
1653the -m switch.
Georg Brandle0230912010-07-30 08:29:39 +00001654
1655Initial commands are read from .pdbrc files in your home directory
1656and in the current directory, if they exist. Commands supplied with
1657-c are executed after commands from .pdbrc files.
1658
1659To let the script run until an exception occurs, use "-c continue".
Georg Brandl2dfec552010-07-30 08:43:32 +00001660To let the script run up to a given line X in the debugged file, use
1661"-c 'until X'"."""
Georg Brandle0230912010-07-30 08:29:39 +00001662
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001663def main():
Georg Brandle0230912010-07-30 08:29:39 +00001664 import getopt
1665
Daniel Hahler855df7f2019-09-12 17:46:37 +02001666 opts, args = getopt.getopt(sys.argv[1:], 'mhc:', ['help', 'command='])
Georg Brandle0230912010-07-30 08:29:39 +00001667
1668 if not args:
1669 print(_usage)
Tim Peters2344fae2001-01-15 00:50:52 +00001670 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001671
Georg Brandle0230912010-07-30 08:29:39 +00001672 commands = []
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001673 run_as_module = False
Georg Brandle0230912010-07-30 08:29:39 +00001674 for opt, optarg in opts:
1675 if opt in ['-h', '--help']:
1676 print(_usage)
1677 sys.exit()
1678 elif opt in ['-c', '--command']:
1679 commands.append(optarg)
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001680 elif opt in ['-m']:
1681 run_as_module = True
Georg Brandle0230912010-07-30 08:29:39 +00001682
1683 mainpyfile = args[0] # Get script filename
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001684 if not run_as_module and not os.path.exists(mainpyfile):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001685 print('Error:', mainpyfile, 'does not exist')
Tim Peters2344fae2001-01-15 00:50:52 +00001686 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001687
Georg Brandle0230912010-07-30 08:29:39 +00001688 sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001689
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001690 if not run_as_module:
Andrey Bienkowski8603dfb2021-01-22 01:19:51 +00001691 mainpyfile = os.path.realpath(mainpyfile)
1692 # Replace pdb's dir with script's dir in front of module search path.
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001693 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001694
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001695 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1696 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl3078df02009-05-05 09:11:31 +00001697 # changed by the user from the command line. There is a "restart" command
1698 # which allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001699 pdb = Pdb()
Georg Brandle0230912010-07-30 08:29:39 +00001700 pdb.rcLines.extend(commands)
Georg Brandl1e30bd32010-07-30 07:21:26 +00001701 while True:
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001702 try:
Mario Corchero9f1e5f12018-01-06 07:53:05 +00001703 if run_as_module:
1704 pdb._runmodule(mainpyfile)
1705 else:
1706 pdb._runscript(mainpyfile)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001707 if pdb._user_requested_quit:
1708 break
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001709 print("The program finished and will be restarted")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001710 except Restart:
1711 print("Restarting", mainpyfile, "with arguments:")
Irit Katriel652bfde2021-04-01 16:25:59 +01001712 print("\t" + " ".join(sys.argv[1:]))
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001713 except SystemExit:
1714 # In most cases SystemExit does not warrant a post-mortem session.
Georg Brandle0230912010-07-30 08:29:39 +00001715 print("The program exited via sys.exit(). Exit status:", end=' ')
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001716 print(sys.exc_info()[1])
Terry Jan Reedyca3f4352015-09-05 19:13:26 -04001717 except SyntaxError:
1718 traceback.print_exc()
1719 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001720 except:
1721 traceback.print_exc()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001722 print("Uncaught exception. Entering post mortem debugging")
1723 print("Running 'cont' or 'step' will restart the program")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001724 t = sys.exc_info()[2]
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001725 pdb.interaction(None, t)
Georg Brandl3078df02009-05-05 09:11:31 +00001726 print("Post mortem debugger finished. The " + mainpyfile +
1727 " will be restarted")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001728
1729
1730# When invoked as main program, invoke the debugger on a script
Guido van Rossumd8faa362007-04-27 19:54:29 +00001731if __name__ == '__main__':
1732 import pdb
1733 pdb.main()