blob: 23bc6dfa16b7a2e43d1919e0e5c983a57210140a [file] [log] [blame]
Guido van Rossumf06ee5f1996-11-27 19:52:01 +00001#! /usr/bin/env python
Guido van Rossumf17361d1996-07-30 16:28:13 +00002
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +00003"""A Python debugger."""
Guido van Rossum92df0c61992-01-14 18:30:15 +00004
Guido van Rossum23efba41992-01-27 16:58:47 +00005# (See pdb.doc for documentation.)
Guido van Rossum921c8241992-01-10 14:54:42 +00006
Guido van Rossum921c8241992-01-10 14:54:42 +00007import sys
8import linecache
Guido van Rossum23efba41992-01-27 16:58:47 +00009import cmd
10import bdb
Alexandre Vassalotti1f2ba4b2008-05-16 07:12:44 +000011from reprlib import Repr
Guido van Rossumb5699c71998-07-20 23:13:54 +000012import os
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000013import re
Barry Warsaw210bd202002-11-05 22:40:20 +000014import pprint
Johannes Gijsbers25b38c82004-10-12 18:12:09 +000015import traceback
Guido van Rossumd8faa362007-04-27 19:54:29 +000016
17
18class Restart(Exception):
19 """Causes a debugger to be restarted for the debugged python program."""
20 pass
21
Guido van Rossumef1b41b2002-09-10 21:57:14 +000022# Create a custom safe Repr instance and increase its maxstring.
23# The default of 30 truncates error messages too easily.
24_repr = Repr()
25_repr.maxstring = 200
26_saferepr = _repr.repr
27
Skip Montanaro352674d2001-02-07 23:14:30 +000028__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
29 "post_mortem", "help"]
30
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000031def find_function(funcname, filename):
Thomas Wouters89f507f2006-12-13 04:49:30 +000032 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
Tim Peters2344fae2001-01-15 00:50:52 +000033 try:
34 fp = open(filename)
35 except IOError:
36 return None
37 # consumer of this info expects the first line to be 1
38 lineno = 1
39 answer = None
40 while 1:
41 line = fp.readline()
42 if line == '':
43 break
44 if cre.match(line):
45 answer = funcname, filename, lineno
46 break
47 lineno = lineno + 1
48 fp.close()
49 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +000050
51
Guido van Rossuma558e371994-11-10 22:27:35 +000052# Interaction prompt line will separate file and call info from code
53# text using value of line_prefix string. A newline and arrow may
54# be to your liking. You can set it once pdb is imported using the
55# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +000056# line_prefix = ': ' # Use this to get the old situation back
57line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +000058
Guido van Rossum23efba41992-01-27 16:58:47 +000059class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +000060
Georg Brandl243ad662009-05-05 09:00:19 +000061 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None):
62 bdb.Bdb.__init__(self, skip=skip)
Thomas Wouters477c8d52006-05-27 19:21:47 +000063 cmd.Cmd.__init__(self, completekey, stdin, stdout)
64 if stdout:
65 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +000066 self.prompt = '(Pdb) '
67 self.aliases = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +000068 self.mainpyfile = ''
69 self._wait_for_mainpyfile = 0
Tim Peters2344fae2001-01-15 00:50:52 +000070 # Try to load readline if it exists
71 try:
72 import readline
73 except ImportError:
74 pass
Guido van Rossum2424f851998-09-11 22:50:09 +000075
Tim Peters2344fae2001-01-15 00:50:52 +000076 # Read $HOME/.pdbrc and ./.pdbrc
77 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +000078 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +000079 envHome = os.environ['HOME']
80 try:
81 rcFile = open(os.path.join(envHome, ".pdbrc"))
82 except IOError:
83 pass
84 else:
85 for line in rcFile.readlines():
86 self.rcLines.append(line)
87 rcFile.close()
88 try:
89 rcFile = open(".pdbrc")
90 except IOError:
91 pass
92 else:
93 for line in rcFile.readlines():
94 self.rcLines.append(line)
95 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +000096
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000097 self.commands = {} # associates a command list to breakpoint numbers
Benjamin Petersond23f8222009-04-05 19:13:16 +000098 self.commands_doprompt = {} # for each bp num, tells if the prompt
99 # must be disp. after execing the cmd list
100 self.commands_silent = {} # for each bp num, tells if the stack trace
101 # must be disp. after execing the cmd list
102 self.commands_defining = False # True while in the process of defining
103 # a command list
104 self.commands_bnum = None # The breakpoint number for which we are
105 # defining a list
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000106
Tim Peters2344fae2001-01-15 00:50:52 +0000107 def reset(self):
108 bdb.Bdb.reset(self)
109 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000110
Tim Peters2344fae2001-01-15 00:50:52 +0000111 def forget(self):
112 self.lineno = None
113 self.stack = []
114 self.curindex = 0
115 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +0000116
Tim Peters2344fae2001-01-15 00:50:52 +0000117 def setup(self, f, t):
118 self.forget()
119 self.stack, self.curindex = self.get_stack(f, t)
120 self.curframe = self.stack[self.curindex][0]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000121 # The f_locals dictionary is updated from the actual frame
122 # locals whenever the .f_locals accessor is called, so we
123 # cache it here to ensure that modifications are not overwritten.
124 self.curframe_locals = self.curframe.f_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000125 self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000126
Tim Peters2344fae2001-01-15 00:50:52 +0000127 # Can be executed earlier than 'setup' if desired
128 def execRcLines(self):
129 if self.rcLines:
130 # Make local copy because of recursion
131 rcLines = self.rcLines
132 # executed only once
133 self.rcLines = []
134 for line in rcLines:
135 line = line[:-1]
Guido van Rossum08454592002-07-12 13:10:53 +0000136 if len(line) > 0 and line[0] != '#':
137 self.onecmd(line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000138
Tim Peters280488b2002-08-23 18:19:30 +0000139 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000140
141 def user_call(self, frame, argument_list):
142 """This method is called when there is the remote possibility
143 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000144 if self._wait_for_mainpyfile:
145 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000146 if self.stop_here(frame):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000147 print('--Call--', file=self.stdout)
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000148 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000149
Tim Peters2344fae2001-01-15 00:50:52 +0000150 def user_line(self, frame):
151 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000152 if self._wait_for_mainpyfile:
153 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
154 or frame.f_lineno<= 0):
155 return
156 self._wait_for_mainpyfile = 0
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000157 if self.bp_commands(frame):
158 self.interaction(frame, None)
159
160 def bp_commands(self,frame):
Georg Brandl3078df02009-05-05 09:11:31 +0000161 """Call every command that was set for the current active breakpoint
162 (if there is one).
163
164 Returns True if the normal interaction function must be called,
165 False otherwise."""
166 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
167 if getattr(self, "currentbp", False) and \
168 self.currentbp in self.commands:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000169 currentbp = self.currentbp
170 self.currentbp = 0
171 lastcmd_back = self.lastcmd
172 self.setup(frame, None)
173 for line in self.commands[currentbp]:
174 self.onecmd(line)
175 self.lastcmd = lastcmd_back
176 if not self.commands_silent[currentbp]:
177 self.print_stack_entry(self.stack[self.curindex])
178 if self.commands_doprompt[currentbp]:
179 self.cmdloop()
180 self.forget()
181 return
182 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000183
Tim Peters2344fae2001-01-15 00:50:52 +0000184 def user_return(self, frame, return_value):
185 """This function is called when a return trap is set here."""
186 frame.f_locals['__return__'] = return_value
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000187 print('--Return--', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000188 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000189
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000190 def user_exception(self, frame, exc_info):
Tim Peters2344fae2001-01-15 00:50:52 +0000191 """This function is called if an exception occurs,
192 but only if we are to stop at or just below this level."""
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000193 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000194 frame.f_locals['__exception__'] = exc_type, exc_value
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000195 exc_type_name = exc_type.__name__
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000196 print(exc_type_name + ':', _saferepr(exc_value), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000197 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000198
Tim Peters2344fae2001-01-15 00:50:52 +0000199 # General interaction function
200
201 def interaction(self, frame, traceback):
202 self.setup(frame, traceback)
203 self.print_stack_entry(self.stack[self.curindex])
204 self.cmdloop()
205 self.forget()
206
Benjamin Petersond23f8222009-04-05 19:13:16 +0000207 def displayhook(self, obj):
208 """Custom displayhook for the exec in default(), which prevents
209 assignment of the _ variable in the builtins.
210 """
211 print(repr(obj))
212
Tim Peters2344fae2001-01-15 00:50:52 +0000213 def default(self, line):
214 if line[:1] == '!': line = line[1:]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000215 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000216 globals = self.curframe.f_globals
217 try:
218 code = compile(line + '\n', '<stdin>', 'single')
Christian Heimes679db4a2008-01-18 09:56:22 +0000219 save_stdout = sys.stdout
220 save_stdin = sys.stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000221 save_displayhook = sys.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000222 try:
223 sys.stdin = self.stdin
224 sys.stdout = self.stdout
Benjamin Petersond23f8222009-04-05 19:13:16 +0000225 sys.displayhook = self.displayhook
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000226 exec(code, globals, locals)
227 finally:
228 sys.stdout = save_stdout
229 sys.stdin = save_stdin
Benjamin Petersond23f8222009-04-05 19:13:16 +0000230 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000231 except:
232 t, v = sys.exc_info()[:2]
233 if type(t) == type(''):
234 exc_type_name = t
235 else: exc_type_name = t.__name__
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000236 print('***', exc_type_name + ':', v, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000237
238 def precmd(self, line):
239 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000240 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000241 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000242 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000243 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000244 line = self.aliases[args[0]]
245 ii = 1
246 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000247 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000248 tmpArg)
249 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000250 line = line.replace("%*", ' '.join(args[1:]))
251 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000252 # split into ';;' separated commands
253 # unless it's an alias command
254 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000255 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000256 if marker >= 0:
257 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000258 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000259 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000260 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000261 return line
262
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000263 def onecmd(self, line):
264 """Interpret the argument as though it had been typed in response
265 to the prompt.
266
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000267 Checks whether this line is typed at the normal prompt or in
268 a breakpoint command list definition.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000269 """
270 if not self.commands_defining:
271 return cmd.Cmd.onecmd(self, line)
272 else:
273 return self.handle_command_def(line)
274
275 def handle_command_def(self,line):
276 """ Handles one command line during command list definition. """
277 cmd, arg, line = self.parseline(line)
278 if cmd == 'silent':
279 self.commands_silent[self.commands_bnum] = True
280 return # continue to handle other cmd def in the cmd list
281 elif cmd == 'end':
282 self.cmdqueue = []
283 return 1 # end of cmd list
284 cmdlist = self.commands[self.commands_bnum]
285 if (arg):
286 cmdlist.append(cmd+' '+arg)
287 else:
288 cmdlist.append(cmd)
289 # Determine if we must stop
290 try:
291 func = getattr(self, 'do_' + cmd)
292 except AttributeError:
293 func = self.default
Georg Brandl3078df02009-05-05 09:11:31 +0000294 # one of the resuming commands
295 if func.__name__ in self.commands_resuming:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000296 self.commands_doprompt[self.commands_bnum] = False
297 self.cmdqueue = []
298 return 1
299 return
300
Tim Peters2344fae2001-01-15 00:50:52 +0000301 # Command definitions, called by cmdloop()
302 # The argument is the remaining string on the command line
303 # Return true to exit from the command loop
304
305 do_h = cmd.Cmd.do_help
306
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000307 def do_commands(self, arg):
Georg Brandl3078df02009-05-05 09:11:31 +0000308 """Defines a list of commands associated to a breakpoint.
309
310 Those commands will be executed whenever the breakpoint causes
311 the program to stop execution."""
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000312 if not arg:
313 bnum = len(bdb.Breakpoint.bpbynumber)-1
314 else:
315 try:
316 bnum = int(arg)
317 except:
Georg Brandl3078df02009-05-05 09:11:31 +0000318 print("Usage : commands [bnum]\n ...\n end",
319 file=self.stdout)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000320 return
321 self.commands_bnum = bnum
322 self.commands[bnum] = []
323 self.commands_doprompt[bnum] = True
324 self.commands_silent[bnum] = False
325 prompt_back = self.prompt
326 self.prompt = '(com) '
327 self.commands_defining = True
328 self.cmdloop()
329 self.commands_defining = False
330 self.prompt = prompt_back
331
Tim Peters2344fae2001-01-15 00:50:52 +0000332 def do_break(self, arg, temporary = 0):
333 # break [ ([filename:]lineno | function) [, "condition"] ]
334 if not arg:
335 if self.breaks: # There's at least one
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000336 print("Num Type Disp Enb Where", file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000337 for bp in bdb.Breakpoint.bpbynumber:
338 if bp:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000339 bp.bpprint(self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000340 return
341 # parse arguments; comma has lowest precedence
342 # and cannot occur in filename
343 filename = None
344 lineno = None
345 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000346 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000347 if comma > 0:
348 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000349 cond = arg[comma+1:].lstrip()
350 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000351 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000352 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000353 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000354 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000355 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000356 f = self.lookupmodule(filename)
357 if not f:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000358 print('*** ', repr(filename), end=' ', file=self.stdout)
359 print('not found from sys.path', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000360 return
361 else:
362 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000363 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000364 try:
365 lineno = int(arg)
Guido van Rossumb940e112007-01-10 16:19:56 +0000366 except ValueError as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000367 print('*** Bad lineno:', arg, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000368 return
369 else:
370 # no colon; can be lineno or function
371 try:
372 lineno = int(arg)
373 except ValueError:
374 try:
375 func = eval(arg,
376 self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +0000377 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000378 except:
379 func = arg
380 try:
Christian Heimesff737952007-11-27 10:40:20 +0000381 if hasattr(func, '__func__'):
382 func = func.__func__
Neal Norwitz221085d2007-02-25 20:55:47 +0000383 code = func.__code__
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000384 #use co_name to identify the bkpt (function names
385 #could be aliased, but co_name is invariant)
386 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000387 lineno = code.co_firstlineno
388 filename = code.co_filename
389 except:
390 # last thing to try
391 (ok, filename, ln) = self.lineinfo(arg)
392 if not ok:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000393 print('*** The specified object', end=' ', file=self.stdout)
394 print(repr(arg), end=' ', file=self.stdout)
395 print('is not a function', file=self.stdout)
396 print('or was not found along sys.path.', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000397 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000398 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000399 lineno = int(ln)
400 if not filename:
401 filename = self.defaultFile()
402 # Check for reasonable breakpoint
403 line = self.checkline(filename, lineno)
404 if line:
405 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000406 err = self.set_break(filename, line, temporary, cond, funcname)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000407 if err: print('***', err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000408 else:
409 bp = self.get_breaks(filename, line)[-1]
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000410 print("Breakpoint %d at %s:%d" % (bp.number,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000411 bp.file,
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000412 bp.line), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000413
414 # To be overridden in derived debuggers
415 def defaultFile(self):
416 """Produce a reasonable default."""
417 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000418 if filename == '<string>' and self.mainpyfile:
419 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000420 return filename
421
422 do_b = do_break
423
424 def do_tbreak(self, arg):
425 self.do_break(arg, 1)
426
427 def lineinfo(self, identifier):
428 failed = (None, None, None)
429 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000430 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000431 if len(idstring) == 1:
432 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000433 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000434 elif len(idstring) == 3:
435 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000436 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000437 else:
438 return failed
439 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000440 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000441 # Protection for derived debuggers
442 if parts[0] == 'self':
443 del parts[0]
444 if len(parts) == 0:
445 return failed
446 # Best first guess at file to look at
447 fname = self.defaultFile()
448 if len(parts) == 1:
449 item = parts[0]
450 else:
451 # More than one part.
452 # First is module, second is method/class
453 f = self.lookupmodule(parts[0])
454 if f:
455 fname = f
456 item = parts[1]
457 answer = find_function(item, fname)
458 return answer or failed
459
460 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000461 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000462
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000463 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
464 line or EOF). Warning: testing is not comprehensive.
465 """
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000466 line = linecache.getline(filename, lineno, self.curframe.f_globals)
Tim Peters2344fae2001-01-15 00:50:52 +0000467 if not line:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000468 print('End of file', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000469 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000470 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000471 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000472 if (not line or (line[0] == '#') or
473 (line[:3] == '"""') or line[:3] == "'''"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000474 print('*** Blank or comment', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000475 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000476 return lineno
477
478 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000479 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000480 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000481 try:
482 i = int(i)
483 except ValueError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000484 print('Breakpoint index %r is not a number' % i, file=self.stdout)
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000485 continue
486
487 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000488 print('No breakpoint numbered', i, file=self.stdout)
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000489 continue
490
491 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000492 if bp:
493 bp.enable()
494
495 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000496 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000497 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000498 try:
499 i = int(i)
500 except ValueError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000501 print('Breakpoint index %r is not a number' % i, file=self.stdout)
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000502 continue
Tim Petersf545baa2003-06-15 23:26:30 +0000503
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000504 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000505 print('No breakpoint numbered', i, file=self.stdout)
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000506 continue
507
508 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000509 if bp:
510 bp.disable()
511
512 def do_condition(self, arg):
513 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000514 args = arg.split(' ', 1)
Thomas Woutersb2137042007-02-01 18:02:27 +0000515 try:
516 bpnum = int(args[0].strip())
517 except ValueError:
518 # something went wrong
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000519 print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000520 return
Tim Peters2344fae2001-01-15 00:50:52 +0000521 try:
522 cond = args[1]
523 except:
524 cond = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000525 try:
526 bp = bdb.Breakpoint.bpbynumber[bpnum]
527 except IndexError:
Neal Norwitz752abd02008-05-13 04:55:24 +0000528 print('Breakpoint index %r is not valid' % args[0],
529 file=self.stdout)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000530 return
Tim Peters2344fae2001-01-15 00:50:52 +0000531 if bp:
532 bp.cond = cond
533 if not cond:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000534 print('Breakpoint', bpnum, end=' ', file=self.stdout)
535 print('is now unconditional.', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000536
537 def do_ignore(self,arg):
538 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000539 args = arg.split()
Thomas Woutersb2137042007-02-01 18:02:27 +0000540 try:
541 bpnum = int(args[0].strip())
542 except ValueError:
543 # something went wrong
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000544 print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000545 return
Tim Peters2344fae2001-01-15 00:50:52 +0000546 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000547 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000548 except:
549 count = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +0000550 try:
551 bp = bdb.Breakpoint.bpbynumber[bpnum]
552 except IndexError:
Neal Norwitz752abd02008-05-13 04:55:24 +0000553 print('Breakpoint index %r is not valid' % args[0],
554 file=self.stdout)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000555 return
Tim Peters2344fae2001-01-15 00:50:52 +0000556 if bp:
557 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000558 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000559 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000560 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000561 reply = reply + '%d crossings' % count
562 else:
563 reply = reply + '1 crossing'
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000564 print(reply + ' of breakpoint %d.' % bpnum, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000565 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000566 print('Will stop next time breakpoint', end=' ', file=self.stdout)
567 print(bpnum, 'is reached.', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000568
569 def do_clear(self, arg):
570 """Three possibilities, tried in this order:
571 clear -> clear all breaks, ask for confirmation
572 clear file:lineno -> clear all breaks at file:lineno
573 clear bpno bpno ... -> clear breakpoints by number"""
574 if not arg:
575 try:
Guido van Rossumc5b6ab02007-05-27 09:19:52 +0000576 reply = input('Clear all breaks? ')
Tim Peters2344fae2001-01-15 00:50:52 +0000577 except EOFError:
578 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000579 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000580 if reply in ('y', 'yes'):
581 self.clear_all_breaks()
582 return
583 if ':' in arg:
584 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000585 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000586 filename = arg[:i]
587 arg = arg[i+1:]
588 try:
589 lineno = int(arg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000590 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000591 err = "Invalid line number (%s)" % arg
592 else:
593 err = self.clear_break(filename, lineno)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000594 if err: print('***', err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000595 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000596 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000597 for i in numberlist:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000598 try:
599 i = int(i)
600 except ValueError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000601 print('Breakpoint index %r is not a number' % i, file=self.stdout)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000602 continue
603
Georg Brandl6d2b3462005-08-24 07:36:17 +0000604 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000605 print('No breakpoint numbered', i, file=self.stdout)
Georg Brandl6d2b3462005-08-24 07:36:17 +0000606 continue
Tim Peters2344fae2001-01-15 00:50:52 +0000607 err = self.clear_bpbynumber(i)
608 if err:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000609 print('***', err, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000610 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000611 print('Deleted breakpoint', i, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000612 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
613
614 def do_where(self, arg):
615 self.print_stack_trace()
616 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000617 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000618
619 def do_up(self, arg):
620 if self.curindex == 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000621 print('*** Oldest frame', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000622 else:
623 self.curindex = self.curindex - 1
624 self.curframe = self.stack[self.curindex][0]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000625 self.curframe_locals = self.curframe.f_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000626 self.print_stack_entry(self.stack[self.curindex])
627 self.lineno = None
628 do_u = do_up
629
630 def do_down(self, arg):
631 if self.curindex + 1 == len(self.stack):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000632 print('*** Newest frame', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000633 else:
634 self.curindex = self.curindex + 1
635 self.curframe = self.stack[self.curindex][0]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000636 self.curframe_locals = self.curframe.f_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000637 self.print_stack_entry(self.stack[self.curindex])
638 self.lineno = None
639 do_d = do_down
640
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000641 def do_until(self, arg):
642 self.set_until(self.curframe)
643 return 1
644 do_unt = do_until
645
Tim Peters2344fae2001-01-15 00:50:52 +0000646 def do_step(self, arg):
647 self.set_step()
648 return 1
649 do_s = do_step
650
651 def do_next(self, arg):
652 self.set_next(self.curframe)
653 return 1
654 do_n = do_next
655
Guido van Rossumd8faa362007-04-27 19:54:29 +0000656 def do_run(self, arg):
Georg Brandl3078df02009-05-05 09:11:31 +0000657 """Restart program by raising an exception to be caught in the main
658 debugger loop. If arguments were given, set them in sys.argv."""
Guido van Rossumd8faa362007-04-27 19:54:29 +0000659 if arg:
660 import shlex
661 argv0 = sys.argv[0:1]
662 sys.argv = shlex.split(arg)
663 sys.argv[:0] = argv0
664 raise Restart
665
666 do_restart = do_run
667
Tim Peters2344fae2001-01-15 00:50:52 +0000668 def do_return(self, arg):
669 self.set_return(self.curframe)
670 return 1
671 do_r = do_return
672
673 def do_continue(self, arg):
674 self.set_continue()
675 return 1
676 do_c = do_cont = do_continue
677
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000678 def do_jump(self, arg):
679 if self.curindex + 1 != len(self.stack):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000680 print("*** You can only jump within the bottom frame", file=self.stdout)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000681 return
682 try:
683 arg = int(arg)
684 except ValueError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000685 print("*** The 'jump' command requires a line number.", file=self.stdout)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000686 else:
687 try:
688 # Do the jump, fix up our copy of the stack, and display the
689 # new position
690 self.curframe.f_lineno = arg
691 self.stack[self.curindex] = self.stack[self.curindex][0], arg
692 self.print_stack_entry(self.stack[self.curindex])
Guido van Rossumb940e112007-01-10 16:19:56 +0000693 except ValueError as e:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000694 print('*** Jump failed:', e, file=self.stdout)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000695 do_j = do_jump
696
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000697 def do_debug(self, arg):
698 sys.settrace(None)
699 globals = self.curframe.f_globals
Benjamin Petersond23f8222009-04-05 19:13:16 +0000700 locals = self.curframe_locals
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000701 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +0000702 p.prompt = "(%s) " % self.prompt.strip()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000703 print("ENTERING RECURSIVE DEBUGGER", file=self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +0000704 sys.call_tracing(p.run, (arg, globals, locals))
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000705 print("LEAVING RECURSIVE DEBUGGER", file=self.stdout)
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000706 sys.settrace(self.trace_dispatch)
707 self.lastcmd = p.lastcmd
708
Tim Peters2344fae2001-01-15 00:50:52 +0000709 def do_quit(self, arg):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000710 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000711 self.set_quit()
712 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000713
Tim Peters2344fae2001-01-15 00:50:52 +0000714 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000715 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000716
Guido van Rossumeef26072003-01-13 21:13:55 +0000717 def do_EOF(self, arg):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000718 print(file=self.stdout)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000719 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000720 self.set_quit()
721 return 1
722
Tim Peters2344fae2001-01-15 00:50:52 +0000723 def do_args(self, arg):
Benjamin Petersond23f8222009-04-05 19:13:16 +0000724 co = self.curframe.f_code
725 dict = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000726 n = co.co_argcount
727 if co.co_flags & 4: n = n+1
728 if co.co_flags & 8: n = n+1
729 for i in range(n):
730 name = co.co_varnames[i]
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000731 print(name, '=', end=' ', file=self.stdout)
732 if name in dict: print(dict[name], file=self.stdout)
733 else: print("*** undefined ***", file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000734 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000735
Tim Peters2344fae2001-01-15 00:50:52 +0000736 def do_retval(self, arg):
Benjamin Petersond23f8222009-04-05 19:13:16 +0000737 if '__return__' in self.curframe_locals:
738 print(self.curframe_locals['__return__'], file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000739 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000740 print('*** Not yet returned!', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000741 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000742
Barry Warsaw210bd202002-11-05 22:40:20 +0000743 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000744 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +0000745 return eval(arg, self.curframe.f_globals, self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000746 except:
747 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000748 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000749 exc_type_name = t
750 else: exc_type_name = t.__name__
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000751 print('***', exc_type_name + ':', repr(v), file=self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +0000752 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000753
Barry Warsaw210bd202002-11-05 22:40:20 +0000754 def do_p(self, arg):
755 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000756 print(repr(self._getval(arg)), file=self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +0000757 except:
758 pass
Georg Brandlc9879242007-09-04 07:07:56 +0000759 # make "print" an alias of "p" since print isn't a Python statement anymore
760 do_print = do_p
Barry Warsaw210bd202002-11-05 22:40:20 +0000761
762 def do_pp(self, arg):
763 try:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000764 pprint.pprint(self._getval(arg), self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +0000765 except:
766 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000767
Tim Peters2344fae2001-01-15 00:50:52 +0000768 def do_list(self, arg):
769 self.lastcmd = 'list'
770 last = None
771 if arg:
772 try:
773 x = eval(arg, {}, {})
774 if type(x) == type(()):
775 first, last = x
776 first = int(first)
777 last = int(last)
778 if last < first:
779 # Assume it's a count
780 last = first + last
781 else:
782 first = max(1, int(x) - 5)
783 except:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000784 print('*** Error in argument:', repr(arg), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000785 return
786 elif self.lineno is None:
787 first = max(1, self.curframe.f_lineno - 5)
788 else:
789 first = self.lineno + 1
790 if last is None:
791 last = first + 10
792 filename = self.curframe.f_code.co_filename
793 breaklist = self.get_file_breaks(filename)
794 try:
795 for lineno in range(first, last+1):
Georg Brandl3078df02009-05-05 09:11:31 +0000796 line = linecache.getline(filename, lineno,
797 self.curframe.f_globals)
Tim Peters2344fae2001-01-15 00:50:52 +0000798 if not line:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000799 print('[EOF]', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000800 break
801 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000802 s = repr(lineno).rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000803 if len(s) < 4: s = s + ' '
804 if lineno in breaklist: s = s + 'B'
805 else: s = s + ' '
806 if lineno == self.curframe.f_lineno:
807 s = s + '->'
Guido van Rossumceae3752007-02-09 22:16:54 +0000808 print(s + '\t' + line, end='', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000809 self.lineno = lineno
810 except KeyboardInterrupt:
811 pass
812 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000813
Tim Peters2344fae2001-01-15 00:50:52 +0000814 def do_whatis(self, arg):
815 try:
816 value = eval(arg, self.curframe.f_globals,
Benjamin Petersond23f8222009-04-05 19:13:16 +0000817 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000818 except:
819 t, v = sys.exc_info()[:2]
820 if type(t) == type(''):
821 exc_type_name = t
822 else: exc_type_name = t.__name__
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000823 print('***', exc_type_name + ':', repr(v), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000824 return
825 code = None
826 # Is it a function?
Neal Norwitz221085d2007-02-25 20:55:47 +0000827 try: code = value.__code__
Tim Peters2344fae2001-01-15 00:50:52 +0000828 except: pass
829 if code:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000830 print('Function', code.co_name, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000831 return
832 # Is it an instance method?
Christian Heimesff737952007-11-27 10:40:20 +0000833 try: code = value.__func__.__code__
Tim Peters2344fae2001-01-15 00:50:52 +0000834 except: pass
835 if code:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000836 print('Method', code.co_name, file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000837 return
838 # None of the above...
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000839 print(type(value), file=self.stdout)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000840
Tim Peters2344fae2001-01-15 00:50:52 +0000841 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000842 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000843 if len(args) == 0:
844 keys = self.aliases.keys()
845 keys.sort()
846 for alias in keys:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000847 print("%s = %s" % (alias, self.aliases[alias]), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000848 return
Guido van Rossum08454592002-07-12 13:10:53 +0000849 if args[0] in self.aliases and len(args) == 1:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000850 print("%s = %s" % (args[0], self.aliases[args[0]]), file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000851 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000852 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000853
Tim Peters2344fae2001-01-15 00:50:52 +0000854 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000855 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000856 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000857 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000858 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000859
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000860 #list of all the commands making the program resume execution.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000861 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
862 'do_quit', 'do_jump']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000863
Tim Peters2344fae2001-01-15 00:50:52 +0000864 # Print a traceback starting at the top stack frame.
865 # The most recently entered frame is printed last;
866 # this is different from dbx and gdb, but consistent with
867 # the Python interpreter's stack trace.
868 # It is also consistent with the up/down commands (which are
869 # compatible with dbx and gdb: up moves towards 'main()'
870 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000871
Tim Peters2344fae2001-01-15 00:50:52 +0000872 def print_stack_trace(self):
873 try:
874 for frame_lineno in self.stack:
875 self.print_stack_entry(frame_lineno)
876 except KeyboardInterrupt:
877 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000878
Tim Peters2344fae2001-01-15 00:50:52 +0000879 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
880 frame, lineno = frame_lineno
881 if frame is self.curframe:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000882 print('>', end=' ', file=self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000883 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000884 print(' ', end=' ', file=self.stdout)
885 print(self.format_stack_entry(frame_lineno,
886 prompt_prefix), file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +0000887
Guido van Rossum921c8241992-01-10 14:54:42 +0000888
Tim Peters2344fae2001-01-15 00:50:52 +0000889 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000890
Tim Peters2344fae2001-01-15 00:50:52 +0000891 def help_help(self):
892 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000893
Tim Peters2344fae2001-01-15 00:50:52 +0000894 def help_h(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000895 print("""h(elp)
Tim Peters2344fae2001-01-15 00:50:52 +0000896Without argument, print the list of available commands.
897With a command name as argument, print help about that command
898"help pdb" pipes the full documentation file to the $PAGER
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000899"help exec" gives help on the ! command""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000900
Tim Peters2344fae2001-01-15 00:50:52 +0000901 def help_where(self):
902 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000903
Tim Peters2344fae2001-01-15 00:50:52 +0000904 def help_w(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000905 print("""w(here)
Tim Peters2344fae2001-01-15 00:50:52 +0000906Print a stack trace, with the most recent frame at the bottom.
907An arrow indicates the "current frame", which determines the
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000908context of most commands. 'bt' is an alias for this command.""", file=self.stdout)
Guido van Rossum6bd68352001-01-20 17:57:37 +0000909
910 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000911
Tim Peters2344fae2001-01-15 00:50:52 +0000912 def help_down(self):
913 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000914
Tim Peters2344fae2001-01-15 00:50:52 +0000915 def help_d(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000916 print("""d(own)
Tim Peters2344fae2001-01-15 00:50:52 +0000917Move the current frame one level down in the stack trace
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000918(to a newer frame).""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000919
Tim Peters2344fae2001-01-15 00:50:52 +0000920 def help_up(self):
921 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000922
Tim Peters2344fae2001-01-15 00:50:52 +0000923 def help_u(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000924 print("""u(p)
Tim Peters2344fae2001-01-15 00:50:52 +0000925Move the current frame one level up in the stack trace
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000926(to an older frame).""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000927
Tim Peters2344fae2001-01-15 00:50:52 +0000928 def help_break(self):
929 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000930
Tim Peters2344fae2001-01-15 00:50:52 +0000931 def help_b(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000932 print("""b(reak) ([file:]lineno | function) [, condition]
Tim Peters2344fae2001-01-15 00:50:52 +0000933With a line number argument, set a break there in the current
934file. With a function name, set a break at first executable line
935of that function. Without argument, list all breaks. If a second
936argument is present, it is a string specifying an expression
937which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000938
Tim Peters2344fae2001-01-15 00:50:52 +0000939The line number may be prefixed with a filename and a colon,
940to specify a breakpoint in another file (probably one that
941hasn't been loaded yet). The file is searched for on sys.path;
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000942the .py suffix may be omitted.""", file=self.stdout)
Guido van Rossumb5699c71998-07-20 23:13:54 +0000943
Tim Peters2344fae2001-01-15 00:50:52 +0000944 def help_clear(self):
945 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000946
Tim Peters2344fae2001-01-15 00:50:52 +0000947 def help_cl(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000948 print("cl(ear) filename:lineno", file=self.stdout)
949 print("""cl(ear) [bpnumber [bpnumber...]]
Tim Peters2344fae2001-01-15 00:50:52 +0000950With a space separated list of breakpoint numbers, clear
951those breakpoints. Without argument, clear all breaks (but
952first ask confirmation). With a filename:lineno argument,
Georg Brandld348b252008-01-05 20:00:55 +0000953clear all breaks at that line in that file.""", file=self.stdout)
Guido van Rossumb5699c71998-07-20 23:13:54 +0000954
Tim Peters2344fae2001-01-15 00:50:52 +0000955 def help_tbreak(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000956 print("""tbreak same arguments as break, but breakpoint is
957removed when first hit.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +0000958
Tim Peters2344fae2001-01-15 00:50:52 +0000959 def help_enable(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000960 print("""enable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +0000961Enables the breakpoints given as a space separated list of
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000962bp numbers.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +0000963
Tim Peters2344fae2001-01-15 00:50:52 +0000964 def help_disable(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000965 print("""disable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +0000966Disables the breakpoints given as a space separated list of
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000967bp numbers.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +0000968
Tim Peters2344fae2001-01-15 00:50:52 +0000969 def help_ignore(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000970 print("""ignore bpnumber count
Tim Peters2344fae2001-01-15 00:50:52 +0000971Sets the ignore count for the given breakpoint number. A breakpoint
972becomes active when the ignore count is zero. When non-zero, the
973count is decremented each time the breakpoint is reached and the
974breakpoint is not disabled and any associated condition evaluates
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000975to true.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +0000976
Tim Peters2344fae2001-01-15 00:50:52 +0000977 def help_condition(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000978 print("""condition bpnumber str_condition
Tim Peters2344fae2001-01-15 00:50:52 +0000979str_condition is a string specifying an expression which
980must evaluate to true before the breakpoint is honored.
981If str_condition is absent, any existing condition is removed;
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000982i.e., the breakpoint is made unconditional.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +0000983
Tim Peters2344fae2001-01-15 00:50:52 +0000984 def help_step(self):
985 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000986
Tim Peters2344fae2001-01-15 00:50:52 +0000987 def help_s(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000988 print("""s(tep)
Tim Peters2344fae2001-01-15 00:50:52 +0000989Execute the current line, stop at the first possible occasion
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000990(either in a function that is called or in the current function).""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000991
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000992 def help_until(self):
993 self.help_unt()
994
995 def help_unt(self):
996 print("""unt(il)
997Continue execution until the line with a number greater than the current
998one is reached or until the current frame returns""")
999
Tim Peters2344fae2001-01-15 00:50:52 +00001000 def help_next(self):
1001 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001002
Tim Peters2344fae2001-01-15 00:50:52 +00001003 def help_n(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001004 print("""n(ext)
Tim Peters2344fae2001-01-15 00:50:52 +00001005Continue execution until the next line in the current function
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001006is reached or it returns.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001007
Tim Peters2344fae2001-01-15 00:50:52 +00001008 def help_return(self):
1009 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001010
Tim Peters2344fae2001-01-15 00:50:52 +00001011 def help_r(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001012 print("""r(eturn)
1013Continue execution until the current function returns.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001014
Tim Peters2344fae2001-01-15 00:50:52 +00001015 def help_continue(self):
1016 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001017
Tim Peters2344fae2001-01-15 00:50:52 +00001018 def help_cont(self):
1019 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001020
Tim Peters2344fae2001-01-15 00:50:52 +00001021 def help_c(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001022 print("""c(ont(inue))
1023Continue execution, only stop when a breakpoint is encountered.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001024
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001025 def help_jump(self):
1026 self.help_j()
1027
1028 def help_j(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001029 print("""j(ump) lineno
1030Set the next line that will be executed.""", file=self.stdout)
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001031
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001032 def help_debug(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001033 print("""debug code
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001034Enter a recursive debugger that steps through the code argument
1035(which is an arbitrary expression or statement to be executed
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001036in the current environment).""", file=self.stdout)
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001037
Tim Peters2344fae2001-01-15 00:50:52 +00001038 def help_list(self):
1039 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001040
Tim Peters2344fae2001-01-15 00:50:52 +00001041 def help_l(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001042 print("""l(ist) [first [,last]]
Tim Peters2344fae2001-01-15 00:50:52 +00001043List source code for the current file.
1044Without arguments, list 11 lines around the current line
1045or continue the previous listing.
1046With one argument, list 11 lines starting at that line.
1047With two arguments, list the given range;
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001048if the second argument is less than the first, it is a count.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001049
Tim Peters2344fae2001-01-15 00:50:52 +00001050 def help_args(self):
1051 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001052
Tim Peters2344fae2001-01-15 00:50:52 +00001053 def help_a(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001054 print("""a(rgs)
1055Print the arguments of the current function.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001056
Tim Peters2344fae2001-01-15 00:50:52 +00001057 def help_p(self):
Georg Brandlc9879242007-09-04 07:07:56 +00001058 print("""p(rint) expression
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001059Print the value of the expression.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001060
Barry Warsaw210bd202002-11-05 22:40:20 +00001061 def help_pp(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001062 print("""pp expression
1063Pretty-print the value of the expression.""", file=self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +00001064
Tim Peters2344fae2001-01-15 00:50:52 +00001065 def help_exec(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001066 print("""(!) statement
Tim Peters2344fae2001-01-15 00:50:52 +00001067Execute the (one-line) statement in the context of
1068the current stack frame.
1069The exclamation point can be omitted unless the first word
1070of the statement resembles a debugger command.
1071To assign to a global variable you must always prefix the
1072command with a 'global' command, e.g.:
1073(Pdb) global list_options; list_options = ['-l']
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001074(Pdb)""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001075
Guido van Rossumd8faa362007-04-27 19:54:29 +00001076 def help_run(self):
1077 print("""run [args...]
1078Restart the debugged python program. If a string is supplied, it is
1079splitted with "shlex" and the result is used as the new sys.argv.
1080History, breakpoints, actions and debugger options are preserved.
1081"restart" is an alias for "run".""")
1082
1083 help_restart = help_run
1084
Tim Peters2344fae2001-01-15 00:50:52 +00001085 def help_quit(self):
1086 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001087
Tim Peters2344fae2001-01-15 00:50:52 +00001088 def help_q(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001089 print("""q(uit) or exit - Quit from the debugger.
1090The program being executed is aborted.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001091
Guido van Rossumd1c08f32002-04-15 00:48:24 +00001092 help_exit = help_q
1093
Tim Peters2344fae2001-01-15 00:50:52 +00001094 def help_whatis(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001095 print("""whatis arg
1096Prints the type of the argument.""", file=self.stdout)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001097
Tim Peters2344fae2001-01-15 00:50:52 +00001098 def help_EOF(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001099 print("""EOF
1100Handles the receipt of EOF as a command.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001101
Tim Peters2344fae2001-01-15 00:50:52 +00001102 def help_alias(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001103 print("""alias [name [command [parameter parameter ...] ]]
Tim Peters2344fae2001-01-15 00:50:52 +00001104Creates an alias called 'name' the executes 'command'. The command
1105must *not* be enclosed in quotes. Replaceable parameters are
1106indicated by %1, %2, and so on, while %* is replaced by all the
1107parameters. If no command is given, the current alias for name
1108is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +00001109
Tim Peters2344fae2001-01-15 00:50:52 +00001110Aliases may be nested and can contain anything that can be
1111legally typed at the pdb prompt. Note! You *can* override
1112internal pdb commands with aliases! Those internal commands
1113are then hidden until the alias is removed. Aliasing is recursively
1114applied to the first word of the command line; all other words
1115in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +00001116
Tim Peters2344fae2001-01-15 00:50:52 +00001117Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +00001118
Tim Peters2344fae2001-01-15 00:50:52 +00001119#Print instance variables (usage "pi classInst")
1120alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +00001121
Tim Peters2344fae2001-01-15 00:50:52 +00001122#Print instance variables in self
1123alias ps pi self
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001124""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001125
Tim Peters2344fae2001-01-15 00:50:52 +00001126 def help_unalias(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001127 print("""unalias name
1128Deletes the specified alias.""", file=self.stdout)
Guido van Rossum2424f851998-09-11 22:50:09 +00001129
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001130 def help_commands(self):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001131 print("""commands [bpnumber]
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001132(com) ...
1133(com) end
1134(Pdb)
1135
1136Specify a list of commands for breakpoint number bpnumber. The
1137commands themselves appear on the following lines. Type a line
1138containing just 'end' to terminate the commands.
1139
1140To remove all commands from a breakpoint, type commands and
1141follow it immediately with end; that is, give no commands.
1142
1143With no bpnumber argument, commands refers to the last
1144breakpoint set.
1145
1146You can use breakpoint commands to start your program up again.
1147Simply use the continue command, or step, or any other
1148command that resumes execution.
1149
1150Specifying any command resuming execution (currently continue,
1151step, next, return, jump, quit and their abbreviations) terminates
1152the command list (as if that command was immediately followed by end).
1153This is because any time you resume execution
1154(even with a simple next or step), you may encounter
1155another breakpoint--which could have its own command list, leading to
1156ambiguities about which list to execute.
1157
1158 If you use the 'silent' command in the command list, the
1159usual message about stopping at a breakpoint is not printed. This may
1160be desirable for breakpoints that are to print a specific message and
1161then continue. If none of the other commands print anything, you
1162see no sign that the breakpoint was reached.
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001163""", file=self.stdout)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001164
Tim Peters2344fae2001-01-15 00:50:52 +00001165 def help_pdb(self):
1166 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001167
Tim Peters2344fae2001-01-15 00:50:52 +00001168 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001169 """Helper function for break/clear parsing -- may be overridden.
1170
1171 lookupmodule() translates (possibly incomplete) file or module name
1172 into an absolute file name.
1173 """
1174 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001175 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001176 f = os.path.join(sys.path[0], filename)
1177 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1178 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001179 root, ext = os.path.splitext(filename)
1180 if ext == '':
1181 filename = filename + '.py'
1182 if os.path.isabs(filename):
1183 return filename
1184 for dirname in sys.path:
1185 while os.path.islink(dirname):
1186 dirname = os.readlink(dirname)
1187 fullname = os.path.join(dirname, filename)
1188 if os.path.exists(fullname):
1189 return fullname
1190 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001191
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001192 def _runscript(self, filename):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001193 # The script has to run in __main__ namespace (or imports from
1194 # __main__ will break).
1195 #
1196 # So we clear up the __main__ and set several special variables
1197 # (this gets rid of pdb's globals and cleans old variables on restarts).
1198 import __main__
1199 __main__.__dict__.clear()
1200 __main__.__dict__.update({"__name__" : "__main__",
1201 "__file__" : filename,
1202 "__builtins__": __builtins__,
1203 })
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001204
1205 # When bdb sets tracing, a number of call and line events happens
1206 # BEFORE debugger even reaches user's code (and the exact sequence of
1207 # events depends on python version). So we take special measures to
1208 # avoid stopping before we reach the main script (see user_line and
1209 # user_call for details).
1210 self._wait_for_mainpyfile = 1
1211 self.mainpyfile = self.canonic(filename)
1212 self._user_requested_quit = 0
Georg Brandl7dd803a2007-09-12 19:44:18 +00001213 with open(filename) as fp:
1214 statement = fp.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001215 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001216
Guido van Rossum35771131992-09-08 11:59:04 +00001217# Simplified interface
1218
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001219def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001220 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001221
1222def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001223 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001224
1225def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001226 # B/W compatibility
1227 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001228
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001229def runcall(*args, **kwds):
1230 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001231
Guido van Rossumb6775db1994-08-01 11:34:53 +00001232def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001233 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001234
1235# Post-Mortem interface
1236
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001237def post_mortem(t=None):
1238 # handling the default
1239 if t is None:
1240 # sys.exc_info() returns (type, value, traceback) if an exception is
1241 # being handled, otherwise it returns None
1242 t = sys.exc_info()[2]
1243 if t is None:
1244 raise ValueError("A valid traceback must be passed if no "
1245 "exception is being handled")
1246
Tim Peters2344fae2001-01-15 00:50:52 +00001247 p = Pdb()
1248 p.reset()
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001249 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001250
1251def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001252 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001253
1254
1255# Main program for testing
1256
Guido van Rossum23efba41992-01-27 16:58:47 +00001257TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001258
Guido van Rossum921c8241992-01-10 14:54:42 +00001259def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001260 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001261
1262# print help
1263def help():
Tim Peters2344fae2001-01-15 00:50:52 +00001264 for dirname in sys.path:
1265 fullname = os.path.join(dirname, 'pdb.doc')
1266 if os.path.exists(fullname):
1267 sts = os.system('${PAGER-more} '+fullname)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001268 if sts: print('*** Pager exit status:', sts)
Tim Peters2344fae2001-01-15 00:50:52 +00001269 break
1270 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001271 print('Sorry, can\'t find the help file "pdb.doc"', end=' ')
1272 print('along the Python search path')
Guido van Rossumf17361d1996-07-30 16:28:13 +00001273
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001274def main():
Christian Heimesf6cd9672008-03-26 13:45:42 +00001275 if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001276 print("usage: pdb.py scriptfile [arg] ...")
Tim Peters2344fae2001-01-15 00:50:52 +00001277 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001278
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001279 mainpyfile = sys.argv[1] # Get script filename
1280 if not os.path.exists(mainpyfile):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001281 print('Error:', mainpyfile, 'does not exist')
Tim Peters2344fae2001-01-15 00:50:52 +00001282 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001283
Tim Peters2344fae2001-01-15 00:50:52 +00001284 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001285
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001286 # Replace pdb's dir with script's dir in front of module search path.
1287 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001288
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001289 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1290 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl3078df02009-05-05 09:11:31 +00001291 # changed by the user from the command line. There is a "restart" command
1292 # which allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001293 pdb = Pdb()
1294 while 1:
1295 try:
1296 pdb._runscript(mainpyfile)
1297 if pdb._user_requested_quit:
1298 break
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001299 print("The program finished and will be restarted")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001300 except Restart:
1301 print("Restarting", mainpyfile, "with arguments:")
1302 print("\t" + " ".join(sys.argv[1:]))
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001303 except SystemExit:
1304 # In most cases SystemExit does not warrant a post-mortem session.
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001305 print("The program exited via sys.exit(). Exit status: ", end=' ')
1306 print(sys.exc_info()[1])
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001307 except:
1308 traceback.print_exc()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001309 print("Uncaught exception. Entering post mortem debugging")
1310 print("Running 'cont' or 'step' will restart the program")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001311 t = sys.exc_info()[2]
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001312 pdb.interaction(None, t)
Georg Brandl3078df02009-05-05 09:11:31 +00001313 print("Post mortem debugger finished. The " + mainpyfile +
1314 " will be restarted")
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001315
1316
1317# When invoked as main program, invoke the debugger on a script
Guido van Rossumd8faa362007-04-27 19:54:29 +00001318if __name__ == '__main__':
1319 import pdb
1320 pdb.main()