blob: 80cba9d36c46dc902eeebe989d6daf91435c0179 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#! /usr/bin/env python3
Guido van Rossumf17361d1996-07-30 16:28:13 +00002
Georg Brandl02053ee2010-07-18 10:11:03 +00003"""
4The Python Debugger Pdb
5=======================
Guido van Rossum92df0c61992-01-14 18:30:15 +00006
Georg Brandl02053ee2010-07-18 10:11:03 +00007To use the debugger in its simplest form:
8
9 >>> import pdb
10 >>> pdb.run('<a statement>')
11
12The debugger's prompt is '(Pdb) '. This will stop in the first
13function call in <a statement>.
14
15Alternatively, if a statement terminated with an unhandled exception,
16you can use pdb's post-mortem facility to inspect the contents of the
17traceback:
18
19 >>> <a statement>
20 <exception traceback>
21 >>> import pdb
22 >>> pdb.pm()
23
24The commands recognized by the debugger are listed in the next
25section. Most can be abbreviated as indicated; e.g., h(elp) means
26that 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel',
27nor as 'H' or 'Help' or 'HELP'). Optional arguments are enclosed in
28square brackets. Alternatives in the command syntax are separated
29by a vertical bar (|).
30
31A blank line repeats the previous command literally, except for
32'list', where it lists the next 11 lines.
33
34Commands that the debugger doesn't recognize are assumed to be Python
35statements and are executed in the context of the program being
36debugged. Python statements can also be prefixed with an exclamation
37point ('!'). This is a powerful way to inspect the program being
38debugged; it is even possible to change variables or call functions.
39When an exception occurs in such a statement, the exception name is
40printed but the debugger's state is not changed.
41
42The debugger supports aliases, which can save typing. And aliases can
43have parameters (see the alias help entry) which allows one a certain
44level of adaptability to the context under examination.
45
46Multiple commands may be entered on a single line, separated by the
47pair ';;'. No intelligence is applied to separating the commands; the
48input is split at the first ';;', even if it is in the middle of a
49quoted string.
50
51If a file ".pdbrc" exists in your home directory or in the current
52directory, it is read in and executed as if it had been typed at the
53debugger prompt. This is particularly useful for aliases. If both
54files exist, the one in the home directory is read first and aliases
55defined there can be overriden by the local file.
56
57Aside from aliases, the debugger is not directly programmable; but it
58is implemented as a class from which you can derive your own debugger
59class, which you can make as fancy as you like.
60
61
62Debugger commands
63=================
64
Georg Brandl02053ee2010-07-18 10:11:03 +000065"""
Georg Brandl0d089622010-07-30 16:00:46 +000066# NOTE: the actual command documentation is collected from docstrings of the
67# commands and is appended to __doc__ after the class has been defined.
Guido van Rossum921c8241992-01-10 14:54:42 +000068
Georg Brandl44f2b642010-12-04 16:00:47 +000069import os
70import re
Guido van Rossum921c8241992-01-10 14:54:42 +000071import sys
Guido van Rossum23efba41992-01-27 16:58:47 +000072import cmd
73import bdb
Georg Brandl0a9c3e92010-07-30 18:46:38 +000074import dis
Georg Brandl1acb7462010-12-04 11:20:26 +000075import code
Georg Brandl4c7c3c52012-03-10 22:36:48 +010076import glob
Barry Warsaw210bd202002-11-05 22:40:20 +000077import pprint
Georg Brandl44f2b642010-12-04 16:00:47 +000078import signal
Georg Brandle59ca2a2010-07-30 17:04:28 +000079import inspect
Georg Brandl1acb7462010-12-04 11:20:26 +000080import traceback
81import linecache
Guido van Rossumd8faa362007-04-27 19:54:29 +000082
83
84class Restart(Exception):
85 """Causes a debugger to be restarted for the debugged python program."""
86 pass
87
Skip Montanaro352674d2001-02-07 23:14:30 +000088__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
89 "post_mortem", "help"]
90
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000091def find_function(funcname, filename):
Thomas Wouters89f507f2006-12-13 04:49:30 +000092 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
Tim Peters2344fae2001-01-15 00:50:52 +000093 try:
94 fp = open(filename)
95 except IOError:
96 return None
97 # consumer of this info expects the first line to be 1
98 lineno = 1
99 answer = None
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000100 while True:
Tim Peters2344fae2001-01-15 00:50:52 +0000101 line = fp.readline()
102 if line == '':
103 break
104 if cre.match(line):
105 answer = funcname, filename, lineno
106 break
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000107 lineno += 1
Tim Peters2344fae2001-01-15 00:50:52 +0000108 fp.close()
109 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +0000110
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000111def getsourcelines(obj):
112 lines, lineno = inspect.findsource(obj)
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000113 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000114 # must be a module frame: do not try to cut a block out of it
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000115 return lines, 1
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000116 elif inspect.ismodule(obj):
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000117 return lines, 1
Georg Brandl5ed2b5a2010-07-30 18:08:12 +0000118 return inspect.getblock(lines[lineno:]), lineno+1
Guido van Rossum921c8241992-01-10 14:54:42 +0000119
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000120def lasti2lineno(code, lasti):
121 linestarts = list(dis.findlinestarts(code))
122 linestarts.reverse()
123 for i, lineno in linestarts:
124 if lasti >= i:
125 return lineno
126 return 0
127
128
Georg Brandlcbc79c72010-12-04 16:21:42 +0000129class _rstr(str):
130 """String that doesn't quote its repr."""
131 def __repr__(self):
132 return self
133
134
Guido van Rossuma558e371994-11-10 22:27:35 +0000135# Interaction prompt line will separate file and call info from code
136# text using value of line_prefix string. A newline and arrow may
137# be to your liking. You can set it once pdb is imported using the
138# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +0000139# line_prefix = ': ' # Use this to get the old situation back
140line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +0000141
Guido van Rossum23efba41992-01-27 16:58:47 +0000142class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +0000143
Georg Brandl44f2b642010-12-04 16:00:47 +0000144 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None,
145 nosigint=False):
Georg Brandl243ad662009-05-05 09:00:19 +0000146 bdb.Bdb.__init__(self, skip=skip)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000147 cmd.Cmd.__init__(self, completekey, stdin, stdout)
148 if stdout:
149 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000150 self.prompt = '(Pdb) '
151 self.aliases = {}
Georg Brandlcbc79c72010-12-04 16:21:42 +0000152 self.displaying = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000153 self.mainpyfile = ''
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000154 self._wait_for_mainpyfile = False
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000155 self.tb_lineno = {}
Tim Peters2344fae2001-01-15 00:50:52 +0000156 # Try to load readline if it exists
157 try:
158 import readline
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100159 # remove some common file name delimiters
160 readline.set_completer_delims(' \t\n`@#$%^&*()=+[{]}\\|;:\'",<>?')
Tim Peters2344fae2001-01-15 00:50:52 +0000161 except ImportError:
162 pass
Georg Brandl44f2b642010-12-04 16:00:47 +0000163 self.allow_kbdint = False
164 self.nosigint = nosigint
Guido van Rossum2424f851998-09-11 22:50:09 +0000165
Tim Peters2344fae2001-01-15 00:50:52 +0000166 # Read $HOME/.pdbrc and ./.pdbrc
167 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +0000168 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +0000169 envHome = os.environ['HOME']
170 try:
Florent Xicluna7dde7922010-09-03 19:52:03 +0000171 with open(os.path.join(envHome, ".pdbrc")) as rcFile:
172 self.rcLines.extend(rcFile)
Tim Peters2344fae2001-01-15 00:50:52 +0000173 except IOError:
174 pass
Tim Peters2344fae2001-01-15 00:50:52 +0000175 try:
Florent Xicluna7dde7922010-09-03 19:52:03 +0000176 with open(".pdbrc") as rcFile:
177 self.rcLines.extend(rcFile)
Tim Peters2344fae2001-01-15 00:50:52 +0000178 except IOError:
179 pass
Guido van Rossum23efba41992-01-27 16:58:47 +0000180
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000181 self.commands = {} # associates a command list to breakpoint numbers
Benjamin Petersond23f8222009-04-05 19:13:16 +0000182 self.commands_doprompt = {} # for each bp num, tells if the prompt
183 # must be disp. after execing the cmd list
184 self.commands_silent = {} # for each bp num, tells if the stack trace
185 # must be disp. after execing the cmd list
186 self.commands_defining = False # True while in the process of defining
187 # a command list
188 self.commands_bnum = None # The breakpoint number for which we are
189 # defining a list
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000190
Georg Brandl44f2b642010-12-04 16:00:47 +0000191 def sigint_handler(self, signum, frame):
192 if self.allow_kbdint:
193 raise KeyboardInterrupt
194 self.message("\nProgram interrupted. (Use 'cont' to resume).")
195 self.set_step()
196 self.set_trace(frame)
197 # restore previous signal handler
198 signal.signal(signal.SIGINT, self._previous_sigint_handler)
199
Tim Peters2344fae2001-01-15 00:50:52 +0000200 def reset(self):
201 bdb.Bdb.reset(self)
202 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000203
Tim Peters2344fae2001-01-15 00:50:52 +0000204 def forget(self):
205 self.lineno = None
206 self.stack = []
207 self.curindex = 0
208 self.curframe = None
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000209 self.tb_lineno.clear()
Guido van Rossum2424f851998-09-11 22:50:09 +0000210
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000211 def setup(self, f, tb):
Tim Peters2344fae2001-01-15 00:50:52 +0000212 self.forget()
Georg Brandl0a9c3e92010-07-30 18:46:38 +0000213 self.stack, self.curindex = self.get_stack(f, tb)
214 while tb:
215 # when setting up post-mortem debugging with a traceback, save all
216 # the original line numbers to be displayed along the current line
217 # numbers (which can be different, e.g. due to finally clauses)
218 lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti)
219 self.tb_lineno[tb.tb_frame] = lineno
220 tb = tb.tb_next
Tim Peters2344fae2001-01-15 00:50:52 +0000221 self.curframe = self.stack[self.curindex][0]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000222 # The f_locals dictionary is updated from the actual frame
223 # locals whenever the .f_locals accessor is called, so we
224 # cache it here to ensure that modifications are not overwritten.
225 self.curframe_locals = self.curframe.f_locals
Georg Brandle0230912010-07-30 08:29:39 +0000226 return self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000227
Tim Peters2344fae2001-01-15 00:50:52 +0000228 # Can be executed earlier than 'setup' if desired
229 def execRcLines(self):
Georg Brandle0230912010-07-30 08:29:39 +0000230 if not self.rcLines:
231 return
232 # local copy because of recursion
233 rcLines = self.rcLines
234 rcLines.reverse()
235 # execute every line only once
236 self.rcLines = []
237 while rcLines:
238 line = rcLines.pop().strip()
239 if line and line[0] != '#':
240 if self.onecmd(line):
241 # if onecmd returns True, the command wants to exit
242 # from the interaction, save leftover rc lines
243 # to execute before next interaction
244 self.rcLines += reversed(rcLines)
245 return True
Guido van Rossum2424f851998-09-11 22:50:09 +0000246
Tim Peters280488b2002-08-23 18:19:30 +0000247 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000248
249 def user_call(self, frame, argument_list):
250 """This method is called when there is the remote possibility
251 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000252 if self._wait_for_mainpyfile:
253 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000254 if self.stop_here(frame):
Georg Brandl0d089622010-07-30 16:00:46 +0000255 self.message('--Call--')
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000256 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000257
Tim Peters2344fae2001-01-15 00:50:52 +0000258 def user_line(self, frame):
259 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000260 if self._wait_for_mainpyfile:
261 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000262 or frame.f_lineno <= 0):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000263 return
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000264 self._wait_for_mainpyfile = False
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000265 if self.bp_commands(frame):
266 self.interaction(frame, None)
267
Georg Brandle0230912010-07-30 08:29:39 +0000268 def bp_commands(self, frame):
Georg Brandl3078df02009-05-05 09:11:31 +0000269 """Call every command that was set for the current active breakpoint
270 (if there is one).
271
272 Returns True if the normal interaction function must be called,
273 False otherwise."""
274 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
275 if getattr(self, "currentbp", False) and \
276 self.currentbp in self.commands:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000277 currentbp = self.currentbp
278 self.currentbp = 0
279 lastcmd_back = self.lastcmd
280 self.setup(frame, None)
281 for line in self.commands[currentbp]:
282 self.onecmd(line)
283 self.lastcmd = lastcmd_back
284 if not self.commands_silent[currentbp]:
285 self.print_stack_entry(self.stack[self.curindex])
286 if self.commands_doprompt[currentbp]:
Georg Brandl44f2b642010-12-04 16:00:47 +0000287 self._cmdloop()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000288 self.forget()
289 return
290 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000291
Tim Peters2344fae2001-01-15 00:50:52 +0000292 def user_return(self, frame, return_value):
293 """This function is called when a return trap is set here."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000294 if self._wait_for_mainpyfile:
295 return
Tim Peters2344fae2001-01-15 00:50:52 +0000296 frame.f_locals['__return__'] = return_value
Georg Brandl0d089622010-07-30 16:00:46 +0000297 self.message('--Return--')
Tim Peters2344fae2001-01-15 00:50:52 +0000298 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000299
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000300 def user_exception(self, frame, exc_info):
Tim Peters2344fae2001-01-15 00:50:52 +0000301 """This function is called if an exception occurs,
302 but only if we are to stop at or just below this level."""
Georg Brandl34cc0f52010-07-30 09:43:00 +0000303 if self._wait_for_mainpyfile:
304 return
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000305 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000306 frame.f_locals['__exception__'] = exc_type, exc_value
Georg Brandl0d089622010-07-30 16:00:46 +0000307 self.message(traceback.format_exception_only(exc_type,
308 exc_value)[-1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000309 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000310
Tim Peters2344fae2001-01-15 00:50:52 +0000311 # General interaction function
Georg Brandl44f2b642010-12-04 16:00:47 +0000312 def _cmdloop(self):
313 while True:
314 try:
315 # keyboard interrupts allow for an easy way to cancel
316 # the current command, so allow them during interactive input
317 self.allow_kbdint = True
318 self.cmdloop()
319 self.allow_kbdint = False
320 break
321 except KeyboardInterrupt:
322 self.message('--KeyboardInterrupt--')
Tim Peters2344fae2001-01-15 00:50:52 +0000323
Georg Brandlcbc79c72010-12-04 16:21:42 +0000324 # Called before loop, handles display expressions
325 def preloop(self):
326 displaying = self.displaying.get(self.curframe)
327 if displaying:
328 for expr, oldvalue in displaying.items():
329 newvalue = self._getval_except(expr)
330 # check for identity first; this prevents custom __eq__ to
331 # be called at every loop, and also prevents instances whose
332 # fields are changed to be displayed
333 if newvalue is not oldvalue and newvalue != oldvalue:
334 displaying[expr] = newvalue
335 self.message('display %s: %r [old: %r]' %
336 (expr, newvalue, oldvalue))
337
Tim Peters2344fae2001-01-15 00:50:52 +0000338 def interaction(self, frame, traceback):
Georg Brandle0230912010-07-30 08:29:39 +0000339 if self.setup(frame, traceback):
340 # no interaction desired at this time (happens if .pdbrc contains
341 # a command like "continue")
342 self.forget()
343 return
Tim Peters2344fae2001-01-15 00:50:52 +0000344 self.print_stack_entry(self.stack[self.curindex])
Georg Brandl44f2b642010-12-04 16:00:47 +0000345 self._cmdloop()
Tim Peters2344fae2001-01-15 00:50:52 +0000346 self.forget()
347
Benjamin Petersond23f8222009-04-05 19:13:16 +0000348 def displayhook(self, obj):
349 """Custom displayhook for the exec in default(), which prevents
350 assignment of the _ variable in the builtins.
351 """
Georg Brandl9fa2e022009-09-16 16:40:45 +0000352 # reproduce the behavior of the standard displayhook, not printing None
353 if obj is not None:
Georg Brandl0d089622010-07-30 16:00:46 +0000354 self.message(repr(obj))
Benjamin Petersond23f8222009-04-05 19:13:16 +0000355
Tim Peters2344fae2001-01-15 00:50:52 +0000356 def default(self, line):
357 if line[:1] == '!': line = line[1:]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000358 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000359 globals = self.curframe.f_globals
360 try:
361 code = compile(line + '\n', '<stdin>', 'single')
Christian Heimes679db4a2008-01-18 09:56:22 +0000362 save_stdout = sys.stdout
363 save_stdin = sys.stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000364 save_displayhook = sys.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000365 try:
366 sys.stdin = self.stdin
367 sys.stdout = self.stdout
Benjamin Petersond23f8222009-04-05 19:13:16 +0000368 sys.displayhook = self.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000369 exec(code, globals, locals)
370 finally:
371 sys.stdout = save_stdout
372 sys.stdin = save_stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000373 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000374 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000375 exc_info = sys.exc_info()[:2]
376 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000377
378 def precmd(self, line):
379 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000380 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000381 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000382 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000383 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000384 line = self.aliases[args[0]]
385 ii = 1
386 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000387 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000388 tmpArg)
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000389 ii += 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000390 line = line.replace("%*", ' '.join(args[1:]))
391 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000392 # split into ';;' separated commands
393 # unless it's an alias command
394 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000395 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000396 if marker >= 0:
397 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000398 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000399 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000400 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000401 return line
402
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000403 def onecmd(self, line):
404 """Interpret the argument as though it had been typed in response
405 to the prompt.
406
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000407 Checks whether this line is typed at the normal prompt or in
408 a breakpoint command list definition.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000409 """
410 if not self.commands_defining:
411 return cmd.Cmd.onecmd(self, line)
412 else:
413 return self.handle_command_def(line)
414
Georg Brandlb90ffd82010-07-30 22:20:16 +0000415 def handle_command_def(self, line):
Georg Brandl44f8bf92010-07-30 08:54:49 +0000416 """Handles one command line during command list definition."""
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000417 cmd, arg, line = self.parseline(line)
Georg Brandl44f8bf92010-07-30 08:54:49 +0000418 if not cmd:
419 return
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000420 if cmd == 'silent':
421 self.commands_silent[self.commands_bnum] = True
422 return # continue to handle other cmd def in the cmd list
423 elif cmd == 'end':
424 self.cmdqueue = []
425 return 1 # end of cmd list
426 cmdlist = self.commands[self.commands_bnum]
Georg Brandl44f8bf92010-07-30 08:54:49 +0000427 if arg:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000428 cmdlist.append(cmd+' '+arg)
429 else:
430 cmdlist.append(cmd)
431 # Determine if we must stop
432 try:
433 func = getattr(self, 'do_' + cmd)
434 except AttributeError:
435 func = self.default
Georg Brandl3078df02009-05-05 09:11:31 +0000436 # one of the resuming commands
437 if func.__name__ in self.commands_resuming:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000438 self.commands_doprompt[self.commands_bnum] = False
439 self.cmdqueue = []
440 return 1
441 return
442
Georg Brandl0d089622010-07-30 16:00:46 +0000443 # interface abstraction functions
444
445 def message(self, msg):
446 print(msg, file=self.stdout)
447
448 def error(self, msg):
449 print('***', msg, file=self.stdout)
450
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100451 # Generic completion functions. Individual complete_foo methods can be
452 # assigned below to one of these functions.
453
454 def _complete_location(self, text, line, begidx, endidx):
455 # Complete a file/module/function location for break/tbreak/clear.
456 if line.strip().endswith((':', ',')):
457 # Here comes a line number or a condition which we can't complete.
458 return []
459 # First, try to find matching functions (i.e. expressions).
460 try:
461 ret = self._complete_expression(text, line, begidx, endidx)
462 except Exception:
463 ret = []
464 # Then, try to complete file names as well.
465 globs = glob.glob(text + '*')
466 for fn in globs:
467 if os.path.isdir(fn):
468 ret.append(fn + '/')
469 elif os.path.isfile(fn) and fn.lower().endswith(('.py', '.pyw')):
470 ret.append(fn + ':')
471 return ret
472
473 def _complete_bpnumber(self, text, line, begidx, endidx):
474 # Complete a breakpoint number. (This would be more helpful if we could
475 # display additional info along with the completions, such as file/line
476 # of the breakpoint.)
477 return [str(i) for i, bp in enumerate(bdb.Breakpoint.bpbynumber)
478 if bp is not None and str(i).startswith(text)]
479
480 def _complete_expression(self, text, line, begidx, endidx):
481 # Complete an arbitrary expression.
482 if not self.curframe:
483 return []
484 # Collect globals and locals. It is usually not really sensible to also
485 # complete builtins, and they clutter the namespace quite heavily, so we
486 # leave them out.
487 ns = self.curframe.f_globals.copy()
488 ns.update(self.curframe_locals)
489 if '.' in text:
490 # Walk an attribute chain up to the last part, similar to what
491 # rlcompleter does. This will bail if any of the parts are not
492 # simple attribute access, which is what we want.
493 dotted = text.split('.')
494 try:
495 obj = ns[dotted[0]]
496 for part in dotted[1:-1]:
497 obj = getattr(obj, part)
498 except (KeyError, AttributeError):
499 return []
500 prefix = '.'.join(dotted[:-1]) + '.'
501 return [prefix + n for n in dir(obj) if n.startswith(dotted[-1])]
502 else:
503 # Complete a simple name.
504 return [n for n in ns.keys() if n.startswith(text)]
505
Tim Peters2344fae2001-01-15 00:50:52 +0000506 # Command definitions, called by cmdloop()
507 # The argument is the remaining string on the command line
508 # Return true to exit from the command loop
509
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000510 def do_commands(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000511 """commands [bpnumber]
512 (com) ...
513 (com) end
514 (Pdb)
Georg Brandl3078df02009-05-05 09:11:31 +0000515
Georg Brandl0d089622010-07-30 16:00:46 +0000516 Specify a list of commands for breakpoint number bpnumber.
517 The commands themselves are entered on the following lines.
518 Type a line containing just 'end' to terminate the commands.
519 The commands are executed when the breakpoint is hit.
520
521 To remove all commands from a breakpoint, type commands and
522 follow it immediately with end; that is, give no commands.
523
524 With no bpnumber argument, commands refers to the last
525 breakpoint set.
526
527 You can use breakpoint commands to start your program up
528 again. Simply use the continue command, or step, or any other
529 command that resumes execution.
530
531 Specifying any command resuming execution (currently continue,
532 step, next, return, jump, quit and their abbreviations)
533 terminates the command list (as if that command was
534 immediately followed by end). This is because any time you
535 resume execution (even with a simple next or step), you may
536 encounter another breakpoint -- which could have its own
537 command list, leading to ambiguities about which list to
538 execute.
539
540 If you use the 'silent' command in the command list, the usual
541 message about stopping at a breakpoint is not printed. This
542 may be desirable for breakpoints that are to print a specific
543 message and then continue. If none of the other commands
544 print anything, you will see no sign that the breakpoint was
545 reached.
546 """
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000547 if not arg:
Georg Brandl7410dd12010-07-30 12:01:20 +0000548 bnum = len(bdb.Breakpoint.bpbynumber) - 1
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000549 else:
550 try:
551 bnum = int(arg)
552 except:
Georg Brandl0d089622010-07-30 16:00:46 +0000553 self.error("Usage: commands [bnum]\n ...\n end")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000554 return
555 self.commands_bnum = bnum
Georg Brandlb90ffd82010-07-30 22:20:16 +0000556 # Save old definitions for the case of a keyboard interrupt.
557 if bnum in self.commands:
558 old_command_defs = (self.commands[bnum],
559 self.commands_doprompt[bnum],
560 self.commands_silent[bnum])
561 else:
562 old_command_defs = None
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000563 self.commands[bnum] = []
564 self.commands_doprompt[bnum] = True
565 self.commands_silent[bnum] = False
Georg Brandlb90ffd82010-07-30 22:20:16 +0000566
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000567 prompt_back = self.prompt
568 self.prompt = '(com) '
569 self.commands_defining = True
Georg Brandl44f8bf92010-07-30 08:54:49 +0000570 try:
571 self.cmdloop()
Georg Brandlb90ffd82010-07-30 22:20:16 +0000572 except KeyboardInterrupt:
573 # Restore old definitions.
574 if old_command_defs:
575 self.commands[bnum] = old_command_defs[0]
576 self.commands_doprompt[bnum] = old_command_defs[1]
577 self.commands_silent[bnum] = old_command_defs[2]
578 else:
579 del self.commands[bnum]
580 del self.commands_doprompt[bnum]
581 del self.commands_silent[bnum]
582 self.error('command definition aborted, old commands restored')
Georg Brandl44f8bf92010-07-30 08:54:49 +0000583 finally:
584 self.commands_defining = False
585 self.prompt = prompt_back
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000586
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100587 complete_commands = _complete_bpnumber
588
Tim Peters2344fae2001-01-15 00:50:52 +0000589 def do_break(self, arg, temporary = 0):
Georg Brandl0d089622010-07-30 16:00:46 +0000590 """b(reak) [ ([filename:]lineno | function) [, condition] ]
591 Without argument, list all breaks.
592
593 With a line number argument, set a break at this line in the
594 current file. With a function name, set a break at the first
595 executable line of that function. If a second argument is
596 present, it is a string specifying an expression which must
597 evaluate to true before the breakpoint is honored.
598
599 The line number may be prefixed with a filename and a colon,
600 to specify a breakpoint in another file (probably one that
601 hasn't been loaded yet). The file is searched for on
602 sys.path; the .py suffix may be omitted.
603 """
Tim Peters2344fae2001-01-15 00:50:52 +0000604 if not arg:
605 if self.breaks: # There's at least one
Georg Brandl0d089622010-07-30 16:00:46 +0000606 self.message("Num Type Disp Enb Where")
Tim Peters2344fae2001-01-15 00:50:52 +0000607 for bp in bdb.Breakpoint.bpbynumber:
608 if bp:
Georg Brandl0d089622010-07-30 16:00:46 +0000609 self.message(bp.bpformat())
Tim Peters2344fae2001-01-15 00:50:52 +0000610 return
611 # parse arguments; comma has lowest precedence
612 # and cannot occur in filename
613 filename = None
614 lineno = None
615 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000616 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000617 if comma > 0:
618 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000619 cond = arg[comma+1:].lstrip()
620 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000621 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000622 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000623 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000624 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000625 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000626 f = self.lookupmodule(filename)
627 if not f:
Georg Brandl0d089622010-07-30 16:00:46 +0000628 self.error('%r not found from sys.path' % filename)
Tim Peters2344fae2001-01-15 00:50:52 +0000629 return
630 else:
631 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000632 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000633 try:
634 lineno = int(arg)
Georg Brandlf93390a2010-10-14 07:17:44 +0000635 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000636 self.error('Bad lineno: %s' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000637 return
638 else:
639 # no colon; can be lineno or function
640 try:
641 lineno = int(arg)
642 except ValueError:
643 try:
644 func = eval(arg,
645 self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +0000646 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000647 except:
648 func = arg
649 try:
Christian Heimesff737952007-11-27 10:40:20 +0000650 if hasattr(func, '__func__'):
651 func = func.__func__
Neal Norwitz221085d2007-02-25 20:55:47 +0000652 code = func.__code__
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000653 #use co_name to identify the bkpt (function names
654 #could be aliased, but co_name is invariant)
655 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000656 lineno = code.co_firstlineno
657 filename = code.co_filename
658 except:
659 # last thing to try
660 (ok, filename, ln) = self.lineinfo(arg)
661 if not ok:
Georg Brandl0d089622010-07-30 16:00:46 +0000662 self.error('The specified object %r is not a function '
663 'or was not found along sys.path.' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000664 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000665 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000666 lineno = int(ln)
667 if not filename:
668 filename = self.defaultFile()
669 # Check for reasonable breakpoint
670 line = self.checkline(filename, lineno)
671 if line:
672 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000673 err = self.set_break(filename, line, temporary, cond, funcname)
Georg Brandl0d089622010-07-30 16:00:46 +0000674 if err:
675 self.error(err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000676 else:
677 bp = self.get_breaks(filename, line)[-1]
Georg Brandl0d089622010-07-30 16:00:46 +0000678 self.message("Breakpoint %d at %s:%d" %
679 (bp.number, bp.file, bp.line))
Tim Peters2344fae2001-01-15 00:50:52 +0000680
681 # To be overridden in derived debuggers
682 def defaultFile(self):
683 """Produce a reasonable default."""
684 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000685 if filename == '<string>' and self.mainpyfile:
686 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000687 return filename
688
689 do_b = do_break
690
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100691 complete_break = _complete_location
692 complete_b = _complete_location
693
Tim Peters2344fae2001-01-15 00:50:52 +0000694 def do_tbreak(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000695 """tbreak [ ([filename:]lineno | function) [, condition] ]
696 Same arguments as break, but sets a temporary breakpoint: it
697 is automatically deleted when first hit.
698 """
Tim Peters2344fae2001-01-15 00:50:52 +0000699 self.do_break(arg, 1)
700
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100701 complete_tbreak = _complete_location
702
Tim Peters2344fae2001-01-15 00:50:52 +0000703 def lineinfo(self, identifier):
704 failed = (None, None, None)
705 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000706 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000707 if len(idstring) == 1:
708 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000709 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000710 elif len(idstring) == 3:
711 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000712 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000713 else:
714 return failed
715 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000716 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000717 # Protection for derived debuggers
718 if parts[0] == 'self':
719 del parts[0]
720 if len(parts) == 0:
721 return failed
722 # Best first guess at file to look at
723 fname = self.defaultFile()
724 if len(parts) == 1:
725 item = parts[0]
726 else:
727 # More than one part.
728 # First is module, second is method/class
729 f = self.lookupmodule(parts[0])
730 if f:
731 fname = f
732 item = parts[1]
733 answer = find_function(item, fname)
734 return answer or failed
735
736 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000737 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000738
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000739 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
740 line or EOF). Warning: testing is not comprehensive.
741 """
Georg Brandl1e30bd32010-07-30 07:21:26 +0000742 # this method should be callable before starting debugging, so default
743 # to "no globals" if there is no current frame
744 globs = self.curframe.f_globals if hasattr(self, 'curframe') else None
745 line = linecache.getline(filename, lineno, globs)
Tim Peters2344fae2001-01-15 00:50:52 +0000746 if not line:
Georg Brandl0d089622010-07-30 16:00:46 +0000747 self.message('End of file')
Tim Peters2344fae2001-01-15 00:50:52 +0000748 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000749 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000750 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000751 if (not line or (line[0] == '#') or
752 (line[:3] == '"""') or line[:3] == "'''"):
Georg Brandl0d089622010-07-30 16:00:46 +0000753 self.error('Blank or comment')
Tim Peters2344fae2001-01-15 00:50:52 +0000754 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000755 return lineno
756
757 def do_enable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000758 """enable bpnumber [bpnumber ...]
759 Enables the breakpoints given as a space separated list of
760 breakpoint numbers.
761 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000762 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000763 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000764 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000765 bp = self.get_bpbynumber(i)
766 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000767 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000768 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000769 bp.enable()
Georg Brandl0d089622010-07-30 16:00:46 +0000770 self.message('Enabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000771
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100772 complete_enable = _complete_bpnumber
773
Tim Peters2344fae2001-01-15 00:50:52 +0000774 def do_disable(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000775 """disable bpnumber [bpnumber ...]
776 Disables the breakpoints given as a space separated list of
777 breakpoint numbers. Disabling a breakpoint means it cannot
778 cause the program to stop execution, but unlike clearing a
779 breakpoint, it remains in the list of breakpoints and can be
780 (re-)enabled.
781 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000782 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000783 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000784 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000785 bp = self.get_bpbynumber(i)
786 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000787 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000788 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000789 bp.disable()
Georg Brandl0d089622010-07-30 16:00:46 +0000790 self.message('Disabled %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000791
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100792 complete_disable = _complete_bpnumber
793
Tim Peters2344fae2001-01-15 00:50:52 +0000794 def do_condition(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000795 """condition bpnumber [condition]
796 Set a new condition for the breakpoint, an expression which
797 must evaluate to true before the breakpoint is honored. If
798 condition is absent, any existing condition is removed; i.e.,
799 the breakpoint is made unconditional.
800 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000801 args = arg.split(' ', 1)
Thomas Woutersb2137042007-02-01 18:02:27 +0000802 try:
Tim Peters2344fae2001-01-15 00:50:52 +0000803 cond = args[1]
Georg Brandl7410dd12010-07-30 12:01:20 +0000804 except IndexError:
Tim Peters2344fae2001-01-15 00:50:52 +0000805 cond = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000806 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000807 bp = self.get_bpbynumber(args[0].strip())
Georg Brandl0079ffc2013-10-14 16:08:15 +0200808 except IndexError:
809 self.error('Breakpoint number expected')
Georg Brandl7410dd12010-07-30 12:01:20 +0000810 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000811 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000812 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000813 bp.cond = cond
814 if not cond:
Georg Brandl0d089622010-07-30 16:00:46 +0000815 self.message('Breakpoint %d is now unconditional.' % bp.number)
Georg Brandl7410dd12010-07-30 12:01:20 +0000816 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000817 self.message('New condition set for breakpoint %d.' % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000818
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100819 complete_condition = _complete_bpnumber
820
Georg Brandl7410dd12010-07-30 12:01:20 +0000821 def do_ignore(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000822 """ignore bpnumber [count]
823 Set the ignore count for the given breakpoint number. If
824 count is omitted, the ignore count is set to 0. A breakpoint
825 becomes active when the ignore count is zero. When non-zero,
826 the count is decremented each time the breakpoint is reached
827 and the breakpoint is not disabled and any associated
828 condition evaluates to true.
829 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000830 args = arg.split()
Thomas Woutersb2137042007-02-01 18:02:27 +0000831 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000832 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000833 except:
834 count = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +0000835 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000836 bp = self.get_bpbynumber(args[0].strip())
Georg Brandl0079ffc2013-10-14 16:08:15 +0200837 except IndexError:
838 self.error('Breakpoint number expected')
Georg Brandl7410dd12010-07-30 12:01:20 +0000839 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000840 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000841 else:
Tim Peters2344fae2001-01-15 00:50:52 +0000842 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000843 if count > 0:
Guido van Rossum08454592002-07-12 13:10:53 +0000844 if count > 1:
Georg Brandl0d089622010-07-30 16:00:46 +0000845 countstr = '%d crossings' % count
Tim Peters2344fae2001-01-15 00:50:52 +0000846 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000847 countstr = '1 crossing'
848 self.message('Will ignore next %s of breakpoint %d.' %
849 (countstr, bp.number))
Tim Peters2344fae2001-01-15 00:50:52 +0000850 else:
Georg Brandl0d089622010-07-30 16:00:46 +0000851 self.message('Will stop next time breakpoint %d is reached.'
852 % bp.number)
Tim Peters2344fae2001-01-15 00:50:52 +0000853
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100854 complete_ignore = _complete_bpnumber
855
Tim Peters2344fae2001-01-15 00:50:52 +0000856 def do_clear(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000857 """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]]
858 With a space separated list of breakpoint numbers, clear
859 those breakpoints. Without argument, clear all breaks (but
860 first ask confirmation). With a filename:lineno argument,
861 clear all breaks at that line in that file.
862 """
Tim Peters2344fae2001-01-15 00:50:52 +0000863 if not arg:
864 try:
Guido van Rossumc5b6ab02007-05-27 09:19:52 +0000865 reply = input('Clear all breaks? ')
Tim Peters2344fae2001-01-15 00:50:52 +0000866 except EOFError:
867 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000868 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000869 if reply in ('y', 'yes'):
Georg Brandl7410dd12010-07-30 12:01:20 +0000870 bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp]
Tim Peters2344fae2001-01-15 00:50:52 +0000871 self.clear_all_breaks()
Georg Brandl7410dd12010-07-30 12:01:20 +0000872 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000873 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000874 return
875 if ':' in arg:
876 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000877 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000878 filename = arg[:i]
879 arg = arg[i+1:]
880 try:
881 lineno = int(arg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000882 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000883 err = "Invalid line number (%s)" % arg
884 else:
Georg Brandl7410dd12010-07-30 12:01:20 +0000885 bplist = self.get_breaks(filename, lineno)
Tim Peters2344fae2001-01-15 00:50:52 +0000886 err = self.clear_break(filename, lineno)
Georg Brandl7410dd12010-07-30 12:01:20 +0000887 if err:
Georg Brandl0d089622010-07-30 16:00:46 +0000888 self.error(err)
Georg Brandl7410dd12010-07-30 12:01:20 +0000889 else:
890 for bp in bplist:
Georg Brandl0d089622010-07-30 16:00:46 +0000891 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000892 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000893 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000894 for i in numberlist:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000895 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000896 bp = self.get_bpbynumber(i)
897 except ValueError as err:
Georg Brandl0d089622010-07-30 16:00:46 +0000898 self.error(err)
Tim Peters2344fae2001-01-15 00:50:52 +0000899 else:
Senthil Kumaran6f107042010-11-29 11:54:17 +0000900 self.clear_bpbynumber(i)
Georg Brandl0d089622010-07-30 16:00:46 +0000901 self.message('Deleted %s' % bp)
Tim Peters2344fae2001-01-15 00:50:52 +0000902 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
903
Georg Brandl4c7c3c52012-03-10 22:36:48 +0100904 complete_clear = _complete_location
905 complete_cl = _complete_location
906
Tim Peters2344fae2001-01-15 00:50:52 +0000907 def do_where(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000908 """w(here)
909 Print a stack trace, with the most recent frame at the bottom.
910 An arrow indicates the "current frame", which determines the
911 context of most commands. 'bt' is an alias for this command.
912 """
Tim Peters2344fae2001-01-15 00:50:52 +0000913 self.print_stack_trace()
914 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000915 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000916
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000917 def _select_frame(self, number):
918 assert 0 <= number < len(self.stack)
919 self.curindex = number
920 self.curframe = self.stack[self.curindex][0]
921 self.curframe_locals = self.curframe.f_locals
922 self.print_stack_entry(self.stack[self.curindex])
923 self.lineno = None
924
Tim Peters2344fae2001-01-15 00:50:52 +0000925 def do_up(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000926 """u(p) [count]
927 Move the current frame count (default one) levels up in the
928 stack trace (to an older frame).
929 """
Tim Peters2344fae2001-01-15 00:50:52 +0000930 if self.curindex == 0:
Georg Brandl0d089622010-07-30 16:00:46 +0000931 self.error('Oldest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000932 return
933 try:
934 count = int(arg or 1)
935 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000936 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000937 return
938 if count < 0:
939 newframe = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000940 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000941 newframe = max(0, self.curindex - count)
942 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000943 do_u = do_up
944
945 def do_down(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000946 """d(own) [count]
947 Move the current frame count (default one) levels down in the
948 stack trace (to a newer frame).
949 """
Tim Peters2344fae2001-01-15 00:50:52 +0000950 if self.curindex + 1 == len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +0000951 self.error('Newest frame')
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000952 return
953 try:
954 count = int(arg or 1)
955 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000956 self.error('Invalid frame count (%s)' % arg)
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000957 return
958 if count < 0:
959 newframe = len(self.stack) - 1
Tim Peters2344fae2001-01-15 00:50:52 +0000960 else:
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000961 newframe = min(len(self.stack) - 1, self.curindex + count)
962 self._select_frame(newframe)
Tim Peters2344fae2001-01-15 00:50:52 +0000963 do_d = do_down
964
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000965 def do_until(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000966 """unt(il) [lineno]
967 Without argument, continue execution until the line with a
968 number greater than the current one is reached. With a line
969 number, continue execution until a line with a number greater
970 or equal to that is reached. In both cases, also stop when
971 the current frame returns.
972 """
Georg Brandl2dfec552010-07-30 08:43:32 +0000973 if arg:
974 try:
975 lineno = int(arg)
976 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +0000977 self.error('Error in argument: %r' % arg)
Georg Brandl2dfec552010-07-30 08:43:32 +0000978 return
979 if lineno <= self.curframe.f_lineno:
Georg Brandl0d089622010-07-30 16:00:46 +0000980 self.error('"until" line number is smaller than current '
981 'line number')
Georg Brandl2dfec552010-07-30 08:43:32 +0000982 return
983 else:
984 lineno = None
985 self.set_until(self.curframe, lineno)
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000986 return 1
987 do_unt = do_until
988
Tim Peters2344fae2001-01-15 00:50:52 +0000989 def do_step(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +0000990 """s(tep)
991 Execute the current line, stop at the first possible occasion
992 (either in a function that is called or in the current
993 function).
994 """
Tim Peters2344fae2001-01-15 00:50:52 +0000995 self.set_step()
996 return 1
997 do_s = do_step
998
999 def do_next(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001000 """n(ext)
1001 Continue execution until the next line in the current function
1002 is reached or it returns.
1003 """
Tim Peters2344fae2001-01-15 00:50:52 +00001004 self.set_next(self.curframe)
1005 return 1
1006 do_n = do_next
1007
Guido van Rossumd8faa362007-04-27 19:54:29 +00001008 def do_run(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001009 """run [args...]
1010 Restart the debugged python program. If a string is supplied
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001011 it is split with "shlex", and the result is used as the new
Georg Brandl0d089622010-07-30 16:00:46 +00001012 sys.argv. History, breakpoints, actions and debugger options
1013 are preserved. "restart" is an alias for "run".
1014 """
Guido van Rossumd8faa362007-04-27 19:54:29 +00001015 if arg:
1016 import shlex
1017 argv0 = sys.argv[0:1]
1018 sys.argv = shlex.split(arg)
1019 sys.argv[:0] = argv0
Georg Brandl0d089622010-07-30 16:00:46 +00001020 # this is caught in the main debugger loop
Guido van Rossumd8faa362007-04-27 19:54:29 +00001021 raise Restart
1022
1023 do_restart = do_run
1024
Tim Peters2344fae2001-01-15 00:50:52 +00001025 def do_return(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001026 """r(eturn)
1027 Continue execution until the current function returns.
1028 """
Tim Peters2344fae2001-01-15 00:50:52 +00001029 self.set_return(self.curframe)
1030 return 1
1031 do_r = do_return
1032
1033 def do_continue(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001034 """c(ont(inue))
1035 Continue execution, only stop when a breakpoint is encountered.
1036 """
Georg Brandl44f2b642010-12-04 16:00:47 +00001037 if not self.nosigint:
Andrew Svetlov539ee5d2012-12-04 21:08:28 +02001038 try:
1039 self._previous_sigint_handler = \
1040 signal.signal(signal.SIGINT, self.sigint_handler)
1041 except ValueError:
1042 # ValueError happens when do_continue() is invoked from
1043 # a non-main thread in which case we just continue without
1044 # SIGINT set. Would printing a message here (once) make
1045 # sense?
1046 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001047 self.set_continue()
1048 return 1
1049 do_c = do_cont = do_continue
1050
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001051 def do_jump(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001052 """j(ump) lineno
1053 Set the next line that will be executed. Only available in
1054 the bottom-most frame. This lets you jump back and execute
1055 code again, or jump forward to skip code that you don't want
1056 to run.
1057
1058 It should be noted that not all jumps are allowed -- for
1059 instance it is not possible to jump into the middle of a
1060 for loop or out of a finally clause.
1061 """
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001062 if self.curindex + 1 != len(self.stack):
Georg Brandl0d089622010-07-30 16:00:46 +00001063 self.error('You can only jump within the bottom frame')
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001064 return
1065 try:
1066 arg = int(arg)
1067 except ValueError:
Georg Brandl0d089622010-07-30 16:00:46 +00001068 self.error("The 'jump' command requires a line number")
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001069 else:
1070 try:
1071 # Do the jump, fix up our copy of the stack, and display the
1072 # new position
1073 self.curframe.f_lineno = arg
1074 self.stack[self.curindex] = self.stack[self.curindex][0], arg
1075 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumb940e112007-01-10 16:19:56 +00001076 except ValueError as e:
Georg Brandl0d089622010-07-30 16:00:46 +00001077 self.error('Jump failed: %s' % e)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001078 do_j = do_jump
1079
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001080 def do_debug(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001081 """debug code
1082 Enter a recursive debugger that steps through the code
1083 argument (which is an arbitrary expression or statement to be
1084 executed in the current environment).
1085 """
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001086 sys.settrace(None)
1087 globals = self.curframe.f_globals
Benjamin Petersond23f8222009-04-05 19:13:16 +00001088 locals = self.curframe_locals
Guido van Rossum7736b5b2008-01-15 21:44:53 +00001089 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +00001090 p.prompt = "(%s) " % self.prompt.strip()
Georg Brandl0d089622010-07-30 16:00:46 +00001091 self.message("ENTERING RECURSIVE DEBUGGER")
Guido van Rossumed538d82003-04-09 19:36:34 +00001092 sys.call_tracing(p.run, (arg, globals, locals))
Georg Brandl0d089622010-07-30 16:00:46 +00001093 self.message("LEAVING RECURSIVE DEBUGGER")
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001094 sys.settrace(self.trace_dispatch)
1095 self.lastcmd = p.lastcmd
1096
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001097 complete_debug = _complete_expression
1098
Tim Peters2344fae2001-01-15 00:50:52 +00001099 def do_quit(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001100 """q(uit)\nexit
1101 Quit from the debugger. The program being executed is aborted.
1102 """
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001103 self._user_requested_quit = True
Tim Peters2344fae2001-01-15 00:50:52 +00001104 self.set_quit()
1105 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001106
Tim Peters2344fae2001-01-15 00:50:52 +00001107 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +00001108 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +00001109
Guido van Rossumeef26072003-01-13 21:13:55 +00001110 def do_EOF(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001111 """EOF
1112 Handles the receipt of EOF as a command.
1113 """
1114 self.message('')
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001115 self._user_requested_quit = True
Guido van Rossumeef26072003-01-13 21:13:55 +00001116 self.set_quit()
1117 return 1
1118
Tim Peters2344fae2001-01-15 00:50:52 +00001119 def do_args(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001120 """a(rgs)
1121 Print the argument list of the current function.
1122 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001123 co = self.curframe.f_code
1124 dict = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +00001125 n = co.co_argcount
1126 if co.co_flags & 4: n = n+1
1127 if co.co_flags & 8: n = n+1
1128 for i in range(n):
1129 name = co.co_varnames[i]
Georg Brandl0d089622010-07-30 16:00:46 +00001130 if name in dict:
1131 self.message('%s = %r' % (name, dict[name]))
1132 else:
1133 self.message('%s = *** undefined ***' % (name,))
Tim Peters2344fae2001-01-15 00:50:52 +00001134 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +00001135
Tim Peters2344fae2001-01-15 00:50:52 +00001136 def do_retval(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001137 """retval
1138 Print the return value for the last return of a function.
1139 """
Benjamin Petersond23f8222009-04-05 19:13:16 +00001140 if '__return__' in self.curframe_locals:
Georg Brandl0d089622010-07-30 16:00:46 +00001141 self.message(repr(self.curframe_locals['__return__']))
Tim Peters2344fae2001-01-15 00:50:52 +00001142 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001143 self.error('Not yet returned!')
Tim Peters2344fae2001-01-15 00:50:52 +00001144 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +00001145
Barry Warsaw210bd202002-11-05 22:40:20 +00001146 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +00001147 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +00001148 return eval(arg, self.curframe.f_globals, self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +00001149 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001150 exc_info = sys.exc_info()[:2]
1151 self.error(traceback.format_exception_only(*exc_info)[-1].strip())
Barry Warsaw210bd202002-11-05 22:40:20 +00001152 raise
Guido van Rossum2424f851998-09-11 22:50:09 +00001153
Georg Brandlcbc79c72010-12-04 16:21:42 +00001154 def _getval_except(self, arg, frame=None):
1155 try:
1156 if frame is None:
1157 return eval(arg, self.curframe.f_globals, self.curframe_locals)
1158 else:
1159 return eval(arg, frame.f_globals, frame.f_locals)
1160 except:
1161 exc_info = sys.exc_info()[:2]
1162 err = traceback.format_exception_only(*exc_info)[-1].strip()
1163 return _rstr('** raised %s **' % err)
1164
Barry Warsaw210bd202002-11-05 22:40:20 +00001165 def do_p(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001166 """p(rint) expression
1167 Print the value of the expression.
1168 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001169 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001170 self.message(repr(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001171 except:
1172 pass
Georg Brandlc9879242007-09-04 07:07:56 +00001173 # make "print" an alias of "p" since print isn't a Python statement anymore
1174 do_print = do_p
Barry Warsaw210bd202002-11-05 22:40:20 +00001175
1176 def do_pp(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001177 """pp expression
1178 Pretty-print the value of the expression.
1179 """
Barry Warsaw210bd202002-11-05 22:40:20 +00001180 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001181 self.message(pprint.pformat(self._getval(arg)))
Barry Warsaw210bd202002-11-05 22:40:20 +00001182 except:
1183 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001184
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001185 complete_print = _complete_expression
1186 complete_p = _complete_expression
1187 complete_pp = _complete_expression
1188
Tim Peters2344fae2001-01-15 00:50:52 +00001189 def do_list(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001190 """l(ist) [first [,last] | .]
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001191
1192 List source code for the current file. Without arguments,
1193 list 11 lines around the current line or continue the previous
1194 listing. With . as argument, list 11 lines around the current
1195 line. With one argument, list 11 lines starting at that line.
1196 With two arguments, list the given range; if the second
1197 argument is less than the first, it is a count.
1198
1199 The current line in the current frame is indicated by "->".
1200 If an exception is being debugged, the line where the
1201 exception was originally raised or propagated is indicated by
1202 ">>", if it differs from the current line.
Georg Brandl0d089622010-07-30 16:00:46 +00001203 """
Tim Peters2344fae2001-01-15 00:50:52 +00001204 self.lastcmd = 'list'
1205 last = None
Georg Brandla91a94b2010-07-30 07:14:01 +00001206 if arg and arg != '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001207 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001208 if ',' in arg:
1209 first, last = arg.split(',')
1210 first = int(first.strip())
1211 last = int(last.strip())
Tim Peters2344fae2001-01-15 00:50:52 +00001212 if last < first:
Georg Brandl0d089622010-07-30 16:00:46 +00001213 # assume it's a count
Tim Peters2344fae2001-01-15 00:50:52 +00001214 last = first + last
1215 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001216 first = int(arg.strip())
1217 first = max(1, first - 5)
1218 except ValueError:
1219 self.error('Error in argument: %r' % arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001220 return
Georg Brandla91a94b2010-07-30 07:14:01 +00001221 elif self.lineno is None or arg == '.':
Tim Peters2344fae2001-01-15 00:50:52 +00001222 first = max(1, self.curframe.f_lineno - 5)
1223 else:
1224 first = self.lineno + 1
1225 if last is None:
1226 last = first + 10
1227 filename = self.curframe.f_code.co_filename
1228 breaklist = self.get_file_breaks(filename)
1229 try:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001230 lines = linecache.getlines(filename, self.curframe.f_globals)
1231 self._print_lines(lines[first-1:last], first, breaklist,
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001232 self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001233 self.lineno = min(last, len(lines))
1234 if len(lines) < last:
1235 self.message('[EOF]')
Tim Peters2344fae2001-01-15 00:50:52 +00001236 except KeyboardInterrupt:
1237 pass
1238 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +00001239
Georg Brandle59ca2a2010-07-30 17:04:28 +00001240 def do_longlist(self, arg):
1241 """longlist | ll
1242 List the whole source code for the current function or frame.
1243 """
1244 filename = self.curframe.f_code.co_filename
1245 breaklist = self.get_file_breaks(filename)
1246 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001247 lines, lineno = getsourcelines(self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001248 except IOError as err:
1249 self.error(err)
1250 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001251 self._print_lines(lines, lineno, breaklist, self.curframe)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001252 do_ll = do_longlist
1253
1254 def do_source(self, arg):
1255 """source expression
1256 Try to get source code for the given object and display it.
1257 """
1258 try:
1259 obj = self._getval(arg)
1260 except:
1261 return
1262 try:
Georg Brandl5ed2b5a2010-07-30 18:08:12 +00001263 lines, lineno = getsourcelines(obj)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001264 except (IOError, TypeError) as err:
1265 self.error(err)
1266 return
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001267 self._print_lines(lines, lineno)
Georg Brandle59ca2a2010-07-30 17:04:28 +00001268
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001269 complete_source = _complete_expression
1270
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001271 def _print_lines(self, lines, start, breaks=(), frame=None):
Georg Brandle59ca2a2010-07-30 17:04:28 +00001272 """Print a range of lines."""
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001273 if frame:
1274 current_lineno = frame.f_lineno
1275 exc_lineno = self.tb_lineno.get(frame, -1)
1276 else:
1277 current_lineno = exc_lineno = -1
Georg Brandle59ca2a2010-07-30 17:04:28 +00001278 for lineno, line in enumerate(lines, start):
1279 s = str(lineno).rjust(3)
1280 if len(s) < 4:
1281 s += ' '
1282 if lineno in breaks:
1283 s += 'B'
1284 else:
1285 s += ' '
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001286 if lineno == current_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001287 s += '->'
Georg Brandl0a9c3e92010-07-30 18:46:38 +00001288 elif lineno == exc_lineno:
Georg Brandle59ca2a2010-07-30 17:04:28 +00001289 s += '>>'
1290 self.message(s + '\t' + line.rstrip())
1291
Tim Peters2344fae2001-01-15 00:50:52 +00001292 def do_whatis(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001293 """whatis arg
1294 Print the type of the argument.
1295 """
Tim Peters2344fae2001-01-15 00:50:52 +00001296 try:
Georg Brandl0d089622010-07-30 16:00:46 +00001297 value = self._getval(arg)
Tim Peters2344fae2001-01-15 00:50:52 +00001298 except:
Georg Brandl0d089622010-07-30 16:00:46 +00001299 # _getval() already printed the error
Tim Peters2344fae2001-01-15 00:50:52 +00001300 return
1301 code = None
1302 # Is it a function?
Georg Brandl0d089622010-07-30 16:00:46 +00001303 try:
1304 code = value.__code__
1305 except Exception:
1306 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001307 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001308 self.message('Function %s' % code.co_name)
Tim Peters2344fae2001-01-15 00:50:52 +00001309 return
1310 # Is it an instance method?
Georg Brandl0d089622010-07-30 16:00:46 +00001311 try:
1312 code = value.__func__.__code__
1313 except Exception:
1314 pass
Tim Peters2344fae2001-01-15 00:50:52 +00001315 if code:
Georg Brandl0d089622010-07-30 16:00:46 +00001316 self.message('Method %s' % code.co_name)
1317 return
1318 # Is it a class?
1319 if value.__class__ is type:
1320 self.message('Class %s.%s' % (value.__module__, value.__name__))
Tim Peters2344fae2001-01-15 00:50:52 +00001321 return
1322 # None of the above...
Georg Brandl0d089622010-07-30 16:00:46 +00001323 self.message(type(value))
Guido van Rossum8e2ec561993-07-29 09:37:38 +00001324
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001325 complete_whatis = _complete_expression
1326
Georg Brandlcbc79c72010-12-04 16:21:42 +00001327 def do_display(self, arg):
1328 """display [expression]
1329
1330 Display the value of the expression if it changed, each time execution
1331 stops in the current frame.
1332
1333 Without expression, list all display expressions for the current frame.
1334 """
1335 if not arg:
1336 self.message('Currently displaying:')
1337 for item in self.displaying.get(self.curframe, {}).items():
1338 self.message('%s: %r' % item)
1339 else:
1340 val = self._getval_except(arg)
1341 self.displaying.setdefault(self.curframe, {})[arg] = val
1342 self.message('display %s: %r' % (arg, val))
1343
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001344 complete_display = _complete_expression
1345
Georg Brandlcbc79c72010-12-04 16:21:42 +00001346 def do_undisplay(self, arg):
1347 """undisplay [expression]
1348
1349 Do not display the expression any more in the current frame.
1350
1351 Without expression, clear all display expressions for the current frame.
1352 """
1353 if arg:
1354 try:
1355 del self.displaying.get(self.curframe, {})[arg]
1356 except KeyError:
1357 self.error('not displaying %s' % arg)
1358 else:
1359 self.displaying.pop(self.curframe, None)
1360
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001361 def complete_undisplay(self, text, line, begidx, endidx):
1362 return [e for e in self.displaying.get(self.curframe, {})
1363 if e.startswith(text)]
1364
Georg Brandl1acb7462010-12-04 11:20:26 +00001365 def do_interact(self, arg):
1366 """interact
1367
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001368 Start an interactive interpreter whose global namespace
Georg Brandl1acb7462010-12-04 11:20:26 +00001369 contains all the (global and local) names found in the current scope.
1370 """
1371 ns = self.curframe.f_globals.copy()
1372 ns.update(self.curframe_locals)
1373 code.interact("*interactive*", local=ns)
1374
Tim Peters2344fae2001-01-15 00:50:52 +00001375 def do_alias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001376 """alias [name [command [parameter parameter ...] ]]
1377 Create an alias called 'name' that executes 'command'. The
1378 command must *not* be enclosed in quotes. Replaceable
1379 parameters can be indicated by %1, %2, and so on, while %* is
1380 replaced by all the parameters. If no command is given, the
1381 current alias for name is shown. If no name is given, all
1382 aliases are listed.
1383
1384 Aliases may be nested and can contain anything that can be
1385 legally typed at the pdb prompt. Note! You *can* override
1386 internal pdb commands with aliases! Those internal commands
1387 are then hidden until the alias is removed. Aliasing is
1388 recursively applied to the first word of the command line; all
1389 other words in the line are left alone.
1390
1391 As an example, here are two useful aliases (especially when
1392 placed in the .pdbrc file):
1393
1394 # Print instance variables (usage "pi classInst")
1395 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
1396 # Print instance variables in self
1397 alias ps pi self
1398 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001399 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001400 if len(args) == 0:
Benjamin Petersonbe74a372009-09-11 21:17:13 +00001401 keys = sorted(self.aliases.keys())
Tim Peters2344fae2001-01-15 00:50:52 +00001402 for alias in keys:
Georg Brandl0d089622010-07-30 16:00:46 +00001403 self.message("%s = %s" % (alias, self.aliases[alias]))
Tim Peters2344fae2001-01-15 00:50:52 +00001404 return
Guido van Rossum08454592002-07-12 13:10:53 +00001405 if args[0] in self.aliases and len(args) == 1:
Georg Brandl0d089622010-07-30 16:00:46 +00001406 self.message("%s = %s" % (args[0], self.aliases[args[0]]))
Tim Peters2344fae2001-01-15 00:50:52 +00001407 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001408 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +00001409
Tim Peters2344fae2001-01-15 00:50:52 +00001410 def do_unalias(self, arg):
Georg Brandl0d089622010-07-30 16:00:46 +00001411 """unalias name
1412 Delete the specified alias.
1413 """
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +00001414 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +00001415 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +00001416 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +00001417 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +00001418
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001419 def complete_unalias(self, text, line, begidx, endidx):
1420 return [a for a in self.aliases if a.startswith(text)]
1421
Georg Brandl0d089622010-07-30 16:00:46 +00001422 # List of all the commands making the program resume execution.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001423 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
1424 'do_quit', 'do_jump']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001425
Tim Peters2344fae2001-01-15 00:50:52 +00001426 # Print a traceback starting at the top stack frame.
1427 # The most recently entered frame is printed last;
1428 # this is different from dbx and gdb, but consistent with
1429 # the Python interpreter's stack trace.
1430 # It is also consistent with the up/down commands (which are
1431 # compatible with dbx and gdb: up moves towards 'main()'
1432 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +00001433
Tim Peters2344fae2001-01-15 00:50:52 +00001434 def print_stack_trace(self):
1435 try:
1436 for frame_lineno in self.stack:
1437 self.print_stack_entry(frame_lineno)
1438 except KeyboardInterrupt:
1439 pass
Guido van Rossum2424f851998-09-11 22:50:09 +00001440
Tim Peters2344fae2001-01-15 00:50:52 +00001441 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
1442 frame, lineno = frame_lineno
1443 if frame is self.curframe:
Georg Brandl0d089622010-07-30 16:00:46 +00001444 prefix = '> '
Tim Peters2344fae2001-01-15 00:50:52 +00001445 else:
Georg Brandl0d089622010-07-30 16:00:46 +00001446 prefix = ' '
1447 self.message(prefix +
1448 self.format_stack_entry(frame_lineno, prompt_prefix))
Guido van Rossum2424f851998-09-11 22:50:09 +00001449
Georg Brandl0d089622010-07-30 16:00:46 +00001450 # Provide help
Guido van Rossum921c8241992-01-10 14:54:42 +00001451
Georg Brandl0d089622010-07-30 16:00:46 +00001452 def do_help(self, arg):
1453 """h(elp)
1454 Without argument, print the list of available commands.
1455 With a command name as argument, print help about that command.
1456 "help pdb" shows the full pdb documentation.
1457 "help exec" gives help on the ! command.
1458 """
1459 if not arg:
1460 return cmd.Cmd.do_help(self, arg)
1461 try:
1462 try:
1463 topic = getattr(self, 'help_' + arg)
1464 return topic()
1465 except AttributeError:
1466 command = getattr(self, 'do_' + arg)
1467 except AttributeError:
1468 self.error('No help for %r' % arg)
1469 else:
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001470 if sys.flags.optimize >= 2:
1471 self.error('No help for %r; please do not run Python with -OO '
1472 'if you need command help' % arg)
1473 return
Georg Brandl0d089622010-07-30 16:00:46 +00001474 self.message(command.__doc__.rstrip())
Guido van Rossum921c8241992-01-10 14:54:42 +00001475
Georg Brandl0d089622010-07-30 16:00:46 +00001476 do_h = do_help
Barry Warsaw210bd202002-11-05 22:40:20 +00001477
Tim Peters2344fae2001-01-15 00:50:52 +00001478 def help_exec(self):
Georg Brandl0d089622010-07-30 16:00:46 +00001479 """(!) statement
1480 Execute the (one-line) statement in the context of the current
1481 stack frame. The exclamation point can be omitted unless the
1482 first word of the statement resembles a debugger command. To
1483 assign to a global variable you must always prefix the command
1484 with a 'global' command, e.g.:
1485 (Pdb) global list_options; list_options = ['-l']
1486 (Pdb)
1487 """
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001488 self.message((self.help_exec.__doc__ or '').strip())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001489
Tim Peters2344fae2001-01-15 00:50:52 +00001490 def help_pdb(self):
1491 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001492
Georg Brandl0d089622010-07-30 16:00:46 +00001493 # other helper functions
1494
Tim Peters2344fae2001-01-15 00:50:52 +00001495 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001496 """Helper function for break/clear parsing -- may be overridden.
1497
1498 lookupmodule() translates (possibly incomplete) file or module name
1499 into an absolute file name.
1500 """
1501 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001502 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001503 f = os.path.join(sys.path[0], filename)
1504 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1505 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001506 root, ext = os.path.splitext(filename)
1507 if ext == '':
1508 filename = filename + '.py'
1509 if os.path.isabs(filename):
1510 return filename
1511 for dirname in sys.path:
1512 while os.path.islink(dirname):
1513 dirname = os.readlink(dirname)
1514 fullname = os.path.join(dirname, filename)
1515 if os.path.exists(fullname):
1516 return fullname
1517 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001518
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001519 def _runscript(self, filename):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001520 # The script has to run in __main__ namespace (or imports from
1521 # __main__ will break).
1522 #
1523 # So we clear up the __main__ and set several special variables
1524 # (this gets rid of pdb's globals and cleans old variables on restarts).
1525 import __main__
1526 __main__.__dict__.clear()
1527 __main__.__dict__.update({"__name__" : "__main__",
1528 "__file__" : filename,
1529 "__builtins__": __builtins__,
1530 })
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001531
1532 # When bdb sets tracing, a number of call and line events happens
1533 # BEFORE debugger even reaches user's code (and the exact sequence of
1534 # events depends on python version). So we take special measures to
1535 # avoid stopping before we reach the main script (see user_line and
1536 # user_call for details).
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001537 self._wait_for_mainpyfile = True
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001538 self.mainpyfile = self.canonic(filename)
Georg Brandlac9a2bb2010-11-29 20:19:15 +00001539 self._user_requested_quit = False
Georg Brandld07ac642009-08-13 07:50:57 +00001540 with open(filename, "rb") as fp:
1541 statement = "exec(compile(%r, %r, 'exec'))" % \
1542 (fp.read(), self.mainpyfile)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001543 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001544
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001545# Collect all command help into docstring, if not run with -OO
Georg Brandl0d089622010-07-30 16:00:46 +00001546
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001547if __doc__ is not None:
1548 # unfortunately we can't guess this order from the class definition
1549 _help_order = [
1550 'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable',
1551 'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until',
1552 'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist',
Georg Brandlcbc79c72010-12-04 16:21:42 +00001553 'args', 'print', 'pp', 'whatis', 'source', 'display', 'undisplay',
1554 'interact', 'alias', 'unalias', 'debug', 'quit',
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001555 ]
Georg Brandl0d089622010-07-30 16:00:46 +00001556
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001557 for _command in _help_order:
1558 __doc__ += getattr(Pdb, 'do_' + _command).__doc__.strip() + '\n\n'
1559 __doc__ += Pdb.help_exec.__doc__
Georg Brandl0d089622010-07-30 16:00:46 +00001560
Georg Brandl9e7dbc82010-10-14 07:14:31 +00001561 del _help_order, _command
1562
Georg Brandl0d089622010-07-30 16:00:46 +00001563
Guido van Rossum35771131992-09-08 11:59:04 +00001564# Simplified interface
1565
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001566def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001567 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001568
1569def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001570 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001571
1572def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001573 # B/W compatibility
1574 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001575
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001576def runcall(*args, **kwds):
1577 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001578
Guido van Rossumb6775db1994-08-01 11:34:53 +00001579def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001580 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001581
1582# Post-Mortem interface
1583
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001584def post_mortem(t=None):
1585 # handling the default
1586 if t is None:
1587 # sys.exc_info() returns (type, value, traceback) if an exception is
1588 # being handled, otherwise it returns None
1589 t = sys.exc_info()[2]
Georg Brandl0d089622010-07-30 16:00:46 +00001590 if t is None:
1591 raise ValueError("A valid traceback must be passed if no "
1592 "exception is being handled")
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001593
Tim Peters2344fae2001-01-15 00:50:52 +00001594 p = Pdb()
1595 p.reset()
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001596 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001597
1598def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001599 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001600
1601
1602# Main program for testing
1603
Guido van Rossum23efba41992-01-27 16:58:47 +00001604TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001605
Guido van Rossum921c8241992-01-10 14:54:42 +00001606def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001607 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001608
1609# print help
1610def help():
Georg Brandl02053ee2010-07-18 10:11:03 +00001611 import pydoc
1612 pydoc.pager(__doc__)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001613
Georg Brandle0230912010-07-30 08:29:39 +00001614_usage = """\
1615usage: pdb.py [-c command] ... pyfile [arg] ...
1616
1617Debug the Python program given by pyfile.
1618
1619Initial commands are read from .pdbrc files in your home directory
1620and in the current directory, if they exist. Commands supplied with
1621-c are executed after commands from .pdbrc files.
1622
1623To let the script run until an exception occurs, use "-c continue".
Georg Brandl2dfec552010-07-30 08:43:32 +00001624To let the script run up to a given line X in the debugged file, use
1625"-c 'until X'"."""
Georg Brandle0230912010-07-30 08:29:39 +00001626
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001627def main():
Georg Brandle0230912010-07-30 08:29:39 +00001628 import getopt
1629
1630 opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['--help', '--command='])
1631
1632 if not args:
1633 print(_usage)
Tim Peters2344fae2001-01-15 00:50:52 +00001634 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001635
Georg Brandle0230912010-07-30 08:29:39 +00001636 commands = []
1637 for opt, optarg in opts:
1638 if opt in ['-h', '--help']:
1639 print(_usage)
1640 sys.exit()
1641 elif opt in ['-c', '--command']:
1642 commands.append(optarg)
1643
1644 mainpyfile = args[0] # Get script filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001645 if not os.path.exists(mainpyfile):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001646 print('Error:', mainpyfile, 'does not exist')
Tim Peters2344fae2001-01-15 00:50:52 +00001647 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001648
Georg Brandle0230912010-07-30 08:29:39 +00001649 sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001650
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001651 # Replace pdb's dir with script's dir in front of module search path.
1652 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001653
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001654 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1655 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl3078df02009-05-05 09:11:31 +00001656 # changed by the user from the command line. There is a "restart" command
1657 # which allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001658 pdb = Pdb()
Georg Brandle0230912010-07-30 08:29:39 +00001659 pdb.rcLines.extend(commands)
Georg Brandl1e30bd32010-07-30 07:21:26 +00001660 while True:
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001661 try:
1662 pdb._runscript(mainpyfile)
1663 if pdb._user_requested_quit:
1664 break
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001665 print("The program finished and will be restarted")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001666 except Restart:
1667 print("Restarting", mainpyfile, "with arguments:")
Georg Brandle0230912010-07-30 08:29:39 +00001668 print("\t" + " ".join(args))
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001669 except SystemExit:
1670 # In most cases SystemExit does not warrant a post-mortem session.
Georg Brandle0230912010-07-30 08:29:39 +00001671 print("The program exited via sys.exit(). Exit status:", end=' ')
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001672 print(sys.exc_info()[1])
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001673 except:
1674 traceback.print_exc()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001675 print("Uncaught exception. Entering post mortem debugging")
1676 print("Running 'cont' or 'step' will restart the program")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001677 t = sys.exc_info()[2]
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001678 pdb.interaction(None, t)
Georg Brandl3078df02009-05-05 09:11:31 +00001679 print("Post mortem debugger finished. The " + mainpyfile +
1680 " will be restarted")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001681
1682
1683# When invoked as main program, invoke the debugger on a script
Guido van Rossumd8faa362007-04-27 19:54:29 +00001684if __name__ == '__main__':
1685 import pdb
1686 pdb.main()