blob: c501a38d6c30b3ed13b2a715a233f19ee0521796 [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
Guido van Rossumef1b41b2002-09-10 21:57:14 +000011from repr 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 Rossumef1b41b2002-09-10 21:57:14 +000016# Create a custom safe Repr instance and increase its maxstring.
17# The default of 30 truncates error messages too easily.
18_repr = Repr()
19_repr.maxstring = 200
20_saferepr = _repr.repr
21
Skip Montanaro352674d2001-02-07 23:14:30 +000022__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
23 "post_mortem", "help"]
24
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000025def find_function(funcname, filename):
Tim Peters2344fae2001-01-15 00:50:52 +000026 cre = re.compile(r'def\s+%s\s*[(]' % funcname)
27 try:
28 fp = open(filename)
29 except IOError:
30 return None
31 # consumer of this info expects the first line to be 1
32 lineno = 1
33 answer = None
34 while 1:
35 line = fp.readline()
36 if line == '':
37 break
38 if cre.match(line):
39 answer = funcname, filename, lineno
40 break
41 lineno = lineno + 1
42 fp.close()
43 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +000044
45
Guido van Rossuma558e371994-11-10 22:27:35 +000046# Interaction prompt line will separate file and call info from code
47# text using value of line_prefix string. A newline and arrow may
48# be to your liking. You can set it once pdb is imported using the
49# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +000050# line_prefix = ': ' # Use this to get the old situation back
51line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +000052
Guido van Rossum23efba41992-01-27 16:58:47 +000053class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +000054
Tim Peters2344fae2001-01-15 00:50:52 +000055 def __init__(self):
56 bdb.Bdb.__init__(self)
57 cmd.Cmd.__init__(self)
58 self.prompt = '(Pdb) '
59 self.aliases = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +000060 self.mainpyfile = ''
61 self._wait_for_mainpyfile = 0
Tim Peters2344fae2001-01-15 00:50:52 +000062 # Try to load readline if it exists
63 try:
64 import readline
65 except ImportError:
66 pass
Guido van Rossum2424f851998-09-11 22:50:09 +000067
Tim Peters2344fae2001-01-15 00:50:52 +000068 # Read $HOME/.pdbrc and ./.pdbrc
69 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +000070 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +000071 envHome = os.environ['HOME']
72 try:
73 rcFile = open(os.path.join(envHome, ".pdbrc"))
74 except IOError:
75 pass
76 else:
77 for line in rcFile.readlines():
78 self.rcLines.append(line)
79 rcFile.close()
80 try:
81 rcFile = open(".pdbrc")
82 except IOError:
83 pass
84 else:
85 for line in rcFile.readlines():
86 self.rcLines.append(line)
87 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +000088
Martin v. Löwisbd30f522006-04-17 17:08:37 +000089 self.commands = {} # associates a command list to breakpoint numbers
90 self.commands_doprompt = {} # for each bp num, tells if the prompt must be disp. after execing the cmd list
91 self.commands_silent = {} # for each bp num, tells if the stack trace must be disp. after execing the cmd list
92 self.commands_defining = False # True while in the process of defining a command list
93 self.commands_bnum = None # The breakpoint number for which we are defining a list
94
Tim Peters2344fae2001-01-15 00:50:52 +000095 def reset(self):
96 bdb.Bdb.reset(self)
97 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +000098
Tim Peters2344fae2001-01-15 00:50:52 +000099 def forget(self):
100 self.lineno = None
101 self.stack = []
102 self.curindex = 0
103 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +0000104
Tim Peters2344fae2001-01-15 00:50:52 +0000105 def setup(self, f, t):
106 self.forget()
107 self.stack, self.curindex = self.get_stack(f, t)
108 self.curframe = self.stack[self.curindex][0]
109 self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000110
Tim Peters2344fae2001-01-15 00:50:52 +0000111 # Can be executed earlier than 'setup' if desired
112 def execRcLines(self):
113 if self.rcLines:
114 # Make local copy because of recursion
115 rcLines = self.rcLines
116 # executed only once
117 self.rcLines = []
118 for line in rcLines:
119 line = line[:-1]
Guido van Rossum08454592002-07-12 13:10:53 +0000120 if len(line) > 0 and line[0] != '#':
121 self.onecmd(line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000122
Tim Peters280488b2002-08-23 18:19:30 +0000123 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000124
125 def user_call(self, frame, argument_list):
126 """This method is called when there is the remote possibility
127 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000128 if self._wait_for_mainpyfile:
129 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000130 if self.stop_here(frame):
131 print '--Call--'
132 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000133
Tim Peters2344fae2001-01-15 00:50:52 +0000134 def user_line(self, frame):
135 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000136 if self._wait_for_mainpyfile:
137 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
138 or frame.f_lineno<= 0):
139 return
140 self._wait_for_mainpyfile = 0
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000141 if self.bp_commands(frame):
142 self.interaction(frame, None)
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000143
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000144 def bp_commands(self,frame):
145 """ Call every command that was set for the current active breakpoint (if there is one)
146 Returns True if the normal interaction function must be called, False otherwise """
147 #self.currentbp is set in bdb.py in bdb.break_here if a breakpoint was hit
148 if getattr(self,"currentbp",False) and self.currentbp in self.commands:
149 currentbp = self.currentbp
150 self.currentbp = 0
151 lastcmd_back = self.lastcmd
152 self.setup(frame, None)
153 for line in self.commands[currentbp]:
154 self.onecmd(line)
155 self.lastcmd = lastcmd_back
156 if not self.commands_silent[currentbp]:
157 self.print_stack_entry(self.stack[self.curindex])
158 if self.commands_doprompt[currentbp]:
159 self.cmdloop()
160 self.forget()
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000161 return
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000162 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000163
Tim Peters2344fae2001-01-15 00:50:52 +0000164 def user_return(self, frame, return_value):
165 """This function is called when a return trap is set here."""
166 frame.f_locals['__return__'] = return_value
167 print '--Return--'
168 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000169
Tim Peters2344fae2001-01-15 00:50:52 +0000170 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
171 """This function is called if an exception occurs,
172 but only if we are to stop at or just below this level."""
173 frame.f_locals['__exception__'] = exc_type, exc_value
174 if type(exc_type) == type(''):
175 exc_type_name = exc_type
176 else: exc_type_name = exc_type.__name__
Tim Peters6f8ee592001-02-09 23:28:07 +0000177 print exc_type_name + ':', _saferepr(exc_value)
Tim Peters2344fae2001-01-15 00:50:52 +0000178 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000179
Tim Peters2344fae2001-01-15 00:50:52 +0000180 # General interaction function
181
182 def interaction(self, frame, traceback):
183 self.setup(frame, traceback)
184 self.print_stack_entry(self.stack[self.curindex])
185 self.cmdloop()
186 self.forget()
187
188 def default(self, line):
189 if line[:1] == '!': line = line[1:]
190 locals = self.curframe.f_locals
191 globals = self.curframe.f_globals
192 try:
193 code = compile(line + '\n', '<stdin>', 'single')
194 exec code in globals, locals
195 except:
196 t, v = sys.exc_info()[:2]
197 if type(t) == type(''):
198 exc_type_name = t
199 else: exc_type_name = t.__name__
200 print '***', exc_type_name + ':', v
201
202 def precmd(self, line):
203 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000204 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000205 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000206 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000207 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000208 line = self.aliases[args[0]]
209 ii = 1
210 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000211 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000212 tmpArg)
213 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000214 line = line.replace("%*", ' '.join(args[1:]))
215 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000216 # split into ';;' separated commands
217 # unless it's an alias command
218 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000219 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000220 if marker >= 0:
221 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000222 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000223 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000224 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000225 return line
226
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000227 def onecmd(self, line):
228 """Interpret the argument as though it had been typed in response
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000229 to the prompt.
230
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000231 Checks wether this line is typed in the normal prompt or in a breakpoint command list definition
232 """
233 if not self.commands_defining:
234 return cmd.Cmd.onecmd(self, line)
235 else:
236 return self.handle_command_def(line)
237
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000238 def handle_command_def(self,line):
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000239 """ Handles one command line during command list definition. """
240 cmd, arg, line = self.parseline(line)
241 if cmd == 'silent':
242 self.commands_silent[self.commands_bnum] = True
243 return # continue to handle other cmd def in the cmd list
244 elif cmd == 'end':
245 self.cmdqueue = []
246 return 1 # end of cmd list
247 cmdlist = self.commands[self.commands_bnum]
248 if (arg):
249 cmdlist.append(cmd+' '+arg)
250 else:
251 cmdlist.append(cmd)
252 # Determine if we must stop
253 try:
254 func = getattr(self, 'do_' + cmd)
255 except AttributeError:
256 func = self.default
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000257 if func.func_name in self.commands_resuming : # one of the resuming commands.
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000258 self.commands_doprompt[self.commands_bnum] = False
259 self.cmdqueue = []
260 return 1
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000261 return
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000262
Tim Peters2344fae2001-01-15 00:50:52 +0000263 # Command definitions, called by cmdloop()
264 # The argument is the remaining string on the command line
265 # Return true to exit from the command loop
266
267 do_h = cmd.Cmd.do_help
268
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000269 def do_commands(self, arg):
270 """Defines a list of commands associated to a breakpoint
271 Those commands will be executed whenever the breakpoint causes the program to stop execution."""
272 if not arg:
273 bnum = len(bdb.Breakpoint.bpbynumber)-1
274 else:
275 try:
276 bnum = int(arg)
277 except:
278 print "Usage : commands [bnum]\n ...\n end"
279 return
280 self.commands_bnum = bnum
281 self.commands[bnum] = []
282 self.commands_doprompt[bnum] = True
283 self.commands_silent[bnum] = False
284 prompt_back = self.prompt
285 self.prompt = '(com) '
286 self.commands_defining = True
287 self.cmdloop()
288 self.commands_defining = False
289 self.prompt = prompt_back
290
Tim Peters2344fae2001-01-15 00:50:52 +0000291 def do_break(self, arg, temporary = 0):
292 # break [ ([filename:]lineno | function) [, "condition"] ]
293 if not arg:
294 if self.breaks: # There's at least one
295 print "Num Type Disp Enb Where"
296 for bp in bdb.Breakpoint.bpbynumber:
297 if bp:
298 bp.bpprint()
299 return
300 # parse arguments; comma has lowest precedence
301 # and cannot occur in filename
302 filename = None
303 lineno = None
304 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000305 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000306 if comma > 0:
307 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000308 cond = arg[comma+1:].lstrip()
309 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000310 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000311 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000312 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000313 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000314 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000315 f = self.lookupmodule(filename)
316 if not f:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000317 print '*** ', repr(filename),
Tim Peters2344fae2001-01-15 00:50:52 +0000318 print 'not found from sys.path'
319 return
320 else:
321 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000322 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000323 try:
324 lineno = int(arg)
325 except ValueError, msg:
326 print '*** Bad lineno:', arg
327 return
328 else:
329 # no colon; can be lineno or function
330 try:
331 lineno = int(arg)
332 except ValueError:
333 try:
334 func = eval(arg,
335 self.curframe.f_globals,
336 self.curframe.f_locals)
337 except:
338 func = arg
339 try:
340 if hasattr(func, 'im_func'):
341 func = func.im_func
342 code = func.func_code
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000343 #use co_name to identify the bkpt (function names
344 #could be aliased, but co_name is invariant)
345 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000346 lineno = code.co_firstlineno
347 filename = code.co_filename
348 except:
349 # last thing to try
350 (ok, filename, ln) = self.lineinfo(arg)
351 if not ok:
352 print '*** The specified object',
Walter Dörwald70a6b492004-02-12 17:35:32 +0000353 print repr(arg),
Tim Peters2344fae2001-01-15 00:50:52 +0000354 print 'is not a function'
355 print ('or was not found '
356 'along sys.path.')
357 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000358 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000359 lineno = int(ln)
360 if not filename:
361 filename = self.defaultFile()
362 # Check for reasonable breakpoint
363 line = self.checkline(filename, lineno)
364 if line:
365 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000366 err = self.set_break(filename, line, temporary, cond, funcname)
Tim Peters2344fae2001-01-15 00:50:52 +0000367 if err: print '***', err
368 else:
369 bp = self.get_breaks(filename, line)[-1]
370 print "Breakpoint %d at %s:%d" % (bp.number,
371 bp.file,
372 bp.line)
373
374 # To be overridden in derived debuggers
375 def defaultFile(self):
376 """Produce a reasonable default."""
377 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000378 if filename == '<string>' and self.mainpyfile:
379 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000380 return filename
381
382 do_b = do_break
383
384 def do_tbreak(self, arg):
385 self.do_break(arg, 1)
386
387 def lineinfo(self, identifier):
388 failed = (None, None, None)
389 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000390 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000391 if len(idstring) == 1:
392 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000393 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000394 elif len(idstring) == 3:
395 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000396 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000397 else:
398 return failed
399 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000400 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000401 # Protection for derived debuggers
402 if parts[0] == 'self':
403 del parts[0]
404 if len(parts) == 0:
405 return failed
406 # Best first guess at file to look at
407 fname = self.defaultFile()
408 if len(parts) == 1:
409 item = parts[0]
410 else:
411 # More than one part.
412 # First is module, second is method/class
413 f = self.lookupmodule(parts[0])
414 if f:
415 fname = f
416 item = parts[1]
417 answer = find_function(item, fname)
418 return answer or failed
419
420 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000421 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000422
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000423 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
424 line or EOF). Warning: testing is not comprehensive.
425 """
Tim Peters2344fae2001-01-15 00:50:52 +0000426 line = linecache.getline(filename, lineno)
427 if not line:
428 print 'End of file'
429 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000430 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000431 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000432 if (not line or (line[0] == '#') or
433 (line[:3] == '"""') or line[:3] == "'''"):
Tim Peters2344fae2001-01-15 00:50:52 +0000434 print '*** Blank or comment'
435 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000436 return lineno
437
438 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000439 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000440 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000441 try:
442 i = int(i)
443 except ValueError:
444 print 'Breakpoint index %r is not a number' % i
445 continue
446
447 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
448 print 'No breakpoint numbered', i
449 continue
450
451 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000452 if bp:
453 bp.enable()
454
455 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000456 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000457 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000458 try:
459 i = int(i)
460 except ValueError:
461 print 'Breakpoint index %r is not a number' % i
462 continue
Tim Petersf545baa2003-06-15 23:26:30 +0000463
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000464 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
465 print 'No breakpoint numbered', i
466 continue
467
468 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000469 if bp:
470 bp.disable()
471
472 def do_condition(self, arg):
473 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000474 args = arg.split(' ', 1)
475 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000476 try:
477 cond = args[1]
478 except:
479 cond = None
480 bp = bdb.Breakpoint.bpbynumber[bpnum]
481 if bp:
482 bp.cond = cond
483 if not cond:
484 print 'Breakpoint', bpnum,
485 print 'is now unconditional.'
486
487 def do_ignore(self,arg):
488 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000489 args = arg.split()
490 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000491 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000492 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000493 except:
494 count = 0
495 bp = bdb.Breakpoint.bpbynumber[bpnum]
496 if bp:
497 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000498 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000499 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000500 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000501 reply = reply + '%d crossings' % count
502 else:
503 reply = reply + '1 crossing'
504 print reply + ' of breakpoint %d.' % bpnum
505 else:
506 print 'Will stop next time breakpoint',
507 print bpnum, 'is reached.'
508
509 def do_clear(self, arg):
510 """Three possibilities, tried in this order:
511 clear -> clear all breaks, ask for confirmation
512 clear file:lineno -> clear all breaks at file:lineno
513 clear bpno bpno ... -> clear breakpoints by number"""
514 if not arg:
515 try:
516 reply = raw_input('Clear all breaks? ')
517 except EOFError:
518 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000519 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000520 if reply in ('y', 'yes'):
521 self.clear_all_breaks()
522 return
523 if ':' in arg:
524 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000525 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000526 filename = arg[:i]
527 arg = arg[i+1:]
528 try:
529 lineno = int(arg)
530 except:
531 err = "Invalid line number (%s)" % arg
532 else:
533 err = self.clear_break(filename, lineno)
534 if err: print '***', err
535 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000536 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000537 for i in numberlist:
Georg Brandl6d2b3462005-08-24 07:36:17 +0000538 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
539 print 'No breakpoint numbered', i
540 continue
Tim Peters2344fae2001-01-15 00:50:52 +0000541 err = self.clear_bpbynumber(i)
542 if err:
543 print '***', err
544 else:
Georg Brandl6d2b3462005-08-24 07:36:17 +0000545 print 'Deleted breakpoint', i
Tim Peters2344fae2001-01-15 00:50:52 +0000546 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
547
548 def do_where(self, arg):
549 self.print_stack_trace()
550 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000551 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000552
553 def do_up(self, arg):
554 if self.curindex == 0:
555 print '*** Oldest frame'
556 else:
557 self.curindex = self.curindex - 1
558 self.curframe = self.stack[self.curindex][0]
559 self.print_stack_entry(self.stack[self.curindex])
560 self.lineno = None
561 do_u = do_up
562
563 def do_down(self, arg):
564 if self.curindex + 1 == len(self.stack):
565 print '*** Newest frame'
566 else:
567 self.curindex = self.curindex + 1
568 self.curframe = self.stack[self.curindex][0]
569 self.print_stack_entry(self.stack[self.curindex])
570 self.lineno = None
571 do_d = do_down
572
573 def do_step(self, arg):
574 self.set_step()
575 return 1
576 do_s = do_step
577
578 def do_next(self, arg):
579 self.set_next(self.curframe)
580 return 1
581 do_n = do_next
582
583 def do_return(self, arg):
584 self.set_return(self.curframe)
585 return 1
586 do_r = do_return
587
588 def do_continue(self, arg):
589 self.set_continue()
590 return 1
591 do_c = do_cont = do_continue
592
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000593 def do_jump(self, arg):
594 if self.curindex + 1 != len(self.stack):
595 print "*** You can only jump within the bottom frame"
596 return
597 try:
598 arg = int(arg)
599 except ValueError:
600 print "*** The 'jump' command requires a line number."
601 else:
602 try:
603 # Do the jump, fix up our copy of the stack, and display the
604 # new position
605 self.curframe.f_lineno = arg
606 self.stack[self.curindex] = self.stack[self.curindex][0], arg
607 self.print_stack_entry(self.stack[self.curindex])
608 except ValueError, e:
609 print '*** Jump failed:', e
610 do_j = do_jump
611
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000612 def do_debug(self, arg):
613 sys.settrace(None)
614 globals = self.curframe.f_globals
615 locals = self.curframe.f_locals
Guido van Rossumed538d82003-04-09 19:36:34 +0000616 p = Pdb()
617 p.prompt = "(%s) " % self.prompt.strip()
618 print "ENTERING RECURSIVE DEBUGGER"
619 sys.call_tracing(p.run, (arg, globals, locals))
620 print "LEAVING RECURSIVE DEBUGGER"
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000621 sys.settrace(self.trace_dispatch)
622 self.lastcmd = p.lastcmd
623
Tim Peters2344fae2001-01-15 00:50:52 +0000624 def do_quit(self, arg):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000625 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000626 self.set_quit()
627 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000628
Tim Peters2344fae2001-01-15 00:50:52 +0000629 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000630 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000631
Guido van Rossumeef26072003-01-13 21:13:55 +0000632 def do_EOF(self, arg):
633 print
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000634 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000635 self.set_quit()
636 return 1
637
Tim Peters2344fae2001-01-15 00:50:52 +0000638 def do_args(self, arg):
639 f = self.curframe
640 co = f.f_code
641 dict = f.f_locals
642 n = co.co_argcount
643 if co.co_flags & 4: n = n+1
644 if co.co_flags & 8: n = n+1
645 for i in range(n):
646 name = co.co_varnames[i]
647 print name, '=',
Raymond Hettinger54f02222002-06-01 14:18:47 +0000648 if name in dict: print dict[name]
Tim Peters2344fae2001-01-15 00:50:52 +0000649 else: print "*** undefined ***"
650 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000651
Tim Peters2344fae2001-01-15 00:50:52 +0000652 def do_retval(self, arg):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000653 if '__return__' in self.curframe.f_locals:
Tim Peters2344fae2001-01-15 00:50:52 +0000654 print self.curframe.f_locals['__return__']
655 else:
656 print '*** Not yet returned!'
657 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000658
Barry Warsaw210bd202002-11-05 22:40:20 +0000659 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000660 try:
Barry Warsaw210bd202002-11-05 22:40:20 +0000661 return eval(arg, self.curframe.f_globals,
662 self.curframe.f_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000663 except:
664 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000665 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000666 exc_type_name = t
667 else: exc_type_name = t.__name__
Walter Dörwald70a6b492004-02-12 17:35:32 +0000668 print '***', exc_type_name + ':', repr(v)
Barry Warsaw210bd202002-11-05 22:40:20 +0000669 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000670
Barry Warsaw210bd202002-11-05 22:40:20 +0000671 def do_p(self, arg):
672 try:
673 print repr(self._getval(arg))
674 except:
675 pass
676
677 def do_pp(self, arg):
678 try:
679 pprint.pprint(self._getval(arg))
680 except:
681 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000682
Tim Peters2344fae2001-01-15 00:50:52 +0000683 def do_list(self, arg):
684 self.lastcmd = 'list'
685 last = None
686 if arg:
687 try:
688 x = eval(arg, {}, {})
689 if type(x) == type(()):
690 first, last = x
691 first = int(first)
692 last = int(last)
693 if last < first:
694 # Assume it's a count
695 last = first + last
696 else:
697 first = max(1, int(x) - 5)
698 except:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000699 print '*** Error in argument:', repr(arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000700 return
701 elif self.lineno is None:
702 first = max(1, self.curframe.f_lineno - 5)
703 else:
704 first = self.lineno + 1
705 if last is None:
706 last = first + 10
707 filename = self.curframe.f_code.co_filename
708 breaklist = self.get_file_breaks(filename)
709 try:
710 for lineno in range(first, last+1):
711 line = linecache.getline(filename, lineno)
712 if not line:
713 print '[EOF]'
714 break
715 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000716 s = repr(lineno).rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000717 if len(s) < 4: s = s + ' '
718 if lineno in breaklist: s = s + 'B'
719 else: s = s + ' '
720 if lineno == self.curframe.f_lineno:
721 s = s + '->'
722 print s + '\t' + line,
723 self.lineno = lineno
724 except KeyboardInterrupt:
725 pass
726 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000727
Tim Peters2344fae2001-01-15 00:50:52 +0000728 def do_whatis(self, arg):
729 try:
730 value = eval(arg, self.curframe.f_globals,
731 self.curframe.f_locals)
732 except:
733 t, v = sys.exc_info()[:2]
734 if type(t) == type(''):
735 exc_type_name = t
736 else: exc_type_name = t.__name__
Walter Dörwald70a6b492004-02-12 17:35:32 +0000737 print '***', exc_type_name + ':', repr(v)
Tim Peters2344fae2001-01-15 00:50:52 +0000738 return
739 code = None
740 # Is it a function?
741 try: code = value.func_code
742 except: pass
743 if code:
744 print 'Function', code.co_name
745 return
746 # Is it an instance method?
747 try: code = value.im_func.func_code
748 except: pass
749 if code:
750 print 'Method', code.co_name
751 return
752 # None of the above...
753 print type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000754
Tim Peters2344fae2001-01-15 00:50:52 +0000755 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000756 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000757 if len(args) == 0:
758 keys = self.aliases.keys()
759 keys.sort()
760 for alias in keys:
761 print "%s = %s" % (alias, self.aliases[alias])
762 return
Guido van Rossum08454592002-07-12 13:10:53 +0000763 if args[0] in self.aliases and len(args) == 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000764 print "%s = %s" % (args[0], self.aliases[args[0]])
765 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000766 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000767
Tim Peters2344fae2001-01-15 00:50:52 +0000768 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000769 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000770 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000771 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000772 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000773
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000774 #list of all the commands making the program resume execution.
775 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return', 'do_quit', 'do_jump']
776
Tim Peters2344fae2001-01-15 00:50:52 +0000777 # Print a traceback starting at the top stack frame.
778 # The most recently entered frame is printed last;
779 # this is different from dbx and gdb, but consistent with
780 # the Python interpreter's stack trace.
781 # It is also consistent with the up/down commands (which are
782 # compatible with dbx and gdb: up moves towards 'main()'
783 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000784
Tim Peters2344fae2001-01-15 00:50:52 +0000785 def print_stack_trace(self):
786 try:
787 for frame_lineno in self.stack:
788 self.print_stack_entry(frame_lineno)
789 except KeyboardInterrupt:
790 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000791
Tim Peters2344fae2001-01-15 00:50:52 +0000792 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
793 frame, lineno = frame_lineno
794 if frame is self.curframe:
795 print '>',
796 else:
797 print ' ',
798 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000799
Guido van Rossum921c8241992-01-10 14:54:42 +0000800
Tim Peters2344fae2001-01-15 00:50:52 +0000801 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000802
Tim Peters2344fae2001-01-15 00:50:52 +0000803 def help_help(self):
804 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000805
Tim Peters2344fae2001-01-15 00:50:52 +0000806 def help_h(self):
807 print """h(elp)
808Without argument, print the list of available commands.
809With a command name as argument, print help about that command
810"help pdb" pipes the full documentation file to the $PAGER
811"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000812
Tim Peters2344fae2001-01-15 00:50:52 +0000813 def help_where(self):
814 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000815
Tim Peters2344fae2001-01-15 00:50:52 +0000816 def help_w(self):
817 print """w(here)
818Print a stack trace, with the most recent frame at the bottom.
819An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000820context of most commands. 'bt' is an alias for this command."""
821
822 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000823
Tim Peters2344fae2001-01-15 00:50:52 +0000824 def help_down(self):
825 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000826
Tim Peters2344fae2001-01-15 00:50:52 +0000827 def help_d(self):
828 print """d(own)
829Move the current frame one level down in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000830(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000831
Tim Peters2344fae2001-01-15 00:50:52 +0000832 def help_up(self):
833 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000834
Tim Peters2344fae2001-01-15 00:50:52 +0000835 def help_u(self):
836 print """u(p)
837Move the current frame one level up in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000838(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000839
Tim Peters2344fae2001-01-15 00:50:52 +0000840 def help_break(self):
841 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000842
Tim Peters2344fae2001-01-15 00:50:52 +0000843 def help_b(self):
844 print """b(reak) ([file:]lineno | function) [, condition]
845With a line number argument, set a break there in the current
846file. With a function name, set a break at first executable line
847of that function. Without argument, list all breaks. If a second
848argument is present, it is a string specifying an expression
849which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000850
Tim Peters2344fae2001-01-15 00:50:52 +0000851The line number may be prefixed with a filename and a colon,
852to specify a breakpoint in another file (probably one that
853hasn't been loaded yet). The file is searched for on sys.path;
854the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000855
Tim Peters2344fae2001-01-15 00:50:52 +0000856 def help_clear(self):
857 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000858
Tim Peters2344fae2001-01-15 00:50:52 +0000859 def help_cl(self):
860 print "cl(ear) filename:lineno"
861 print """cl(ear) [bpnumber [bpnumber...]]
862With a space separated list of breakpoint numbers, clear
863those breakpoints. Without argument, clear all breaks (but
864first ask confirmation). With a filename:lineno argument,
865clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000866
Tim Peters2344fae2001-01-15 00:50:52 +0000867Note that the argument is different from previous versions of
868the debugger (in python distributions 1.5.1 and before) where
869a linenumber was used instead of either filename:lineno or
870breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000871
Tim Peters2344fae2001-01-15 00:50:52 +0000872 def help_tbreak(self):
873 print """tbreak same arguments as break, but breakpoint is
874removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000875
Tim Peters2344fae2001-01-15 00:50:52 +0000876 def help_enable(self):
877 print """enable bpnumber [bpnumber ...]
878Enables the breakpoints given as a space separated list of
879bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000880
Tim Peters2344fae2001-01-15 00:50:52 +0000881 def help_disable(self):
882 print """disable bpnumber [bpnumber ...]
883Disables the breakpoints given as a space separated list of
884bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000885
Tim Peters2344fae2001-01-15 00:50:52 +0000886 def help_ignore(self):
887 print """ignore bpnumber count
888Sets the ignore count for the given breakpoint number. A breakpoint
889becomes active when the ignore count is zero. When non-zero, the
890count is decremented each time the breakpoint is reached and the
891breakpoint is not disabled and any associated condition evaluates
892to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000893
Tim Peters2344fae2001-01-15 00:50:52 +0000894 def help_condition(self):
895 print """condition bpnumber str_condition
896str_condition is a string specifying an expression which
897must evaluate to true before the breakpoint is honored.
898If str_condition is absent, any existing condition is removed;
899i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000900
Tim Peters2344fae2001-01-15 00:50:52 +0000901 def help_step(self):
902 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000903
Tim Peters2344fae2001-01-15 00:50:52 +0000904 def help_s(self):
905 print """s(tep)
906Execute the current line, stop at the first possible occasion
907(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000908
Tim Peters2344fae2001-01-15 00:50:52 +0000909 def help_next(self):
910 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000911
Tim Peters2344fae2001-01-15 00:50:52 +0000912 def help_n(self):
913 print """n(ext)
914Continue execution until the next line in the current function
915is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000916
Tim Peters2344fae2001-01-15 00:50:52 +0000917 def help_return(self):
918 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000919
Tim Peters2344fae2001-01-15 00:50:52 +0000920 def help_r(self):
921 print """r(eturn)
922Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000923
Tim Peters2344fae2001-01-15 00:50:52 +0000924 def help_continue(self):
925 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000926
Tim Peters2344fae2001-01-15 00:50:52 +0000927 def help_cont(self):
928 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000929
Tim Peters2344fae2001-01-15 00:50:52 +0000930 def help_c(self):
931 print """c(ont(inue))
932Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000933
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000934 def help_jump(self):
935 self.help_j()
936
937 def help_j(self):
938 print """j(ump) lineno
939Set the next line that will be executed."""
940
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000941 def help_debug(self):
942 print """debug code
943Enter a recursive debugger that steps through the code argument
944(which is an arbitrary expression or statement to be executed
945in the current environment)."""
946
Tim Peters2344fae2001-01-15 00:50:52 +0000947 def help_list(self):
948 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000949
Tim Peters2344fae2001-01-15 00:50:52 +0000950 def help_l(self):
951 print """l(ist) [first [,last]]
952List source code for the current file.
953Without arguments, list 11 lines around the current line
954or continue the previous listing.
955With one argument, list 11 lines starting at that line.
956With two arguments, list the given range;
957if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000958
Tim Peters2344fae2001-01-15 00:50:52 +0000959 def help_args(self):
960 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000961
Tim Peters2344fae2001-01-15 00:50:52 +0000962 def help_a(self):
963 print """a(rgs)
964Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000965
Tim Peters2344fae2001-01-15 00:50:52 +0000966 def help_p(self):
967 print """p expression
968Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000969
Barry Warsaw210bd202002-11-05 22:40:20 +0000970 def help_pp(self):
971 print """pp expression
972Pretty-print the value of the expression."""
973
Tim Peters2344fae2001-01-15 00:50:52 +0000974 def help_exec(self):
975 print """(!) statement
976Execute the (one-line) statement in the context of
977the current stack frame.
978The exclamation point can be omitted unless the first word
979of the statement resembles a debugger command.
980To assign to a global variable you must always prefix the
981command with a 'global' command, e.g.:
982(Pdb) global list_options; list_options = ['-l']
983(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000984
Tim Peters2344fae2001-01-15 00:50:52 +0000985 def help_quit(self):
986 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000987
Tim Peters2344fae2001-01-15 00:50:52 +0000988 def help_q(self):
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000989 print """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +0000990The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000991
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000992 help_exit = help_q
993
Tim Peters2344fae2001-01-15 00:50:52 +0000994 def help_whatis(self):
995 print """whatis arg
996Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000997
Tim Peters2344fae2001-01-15 00:50:52 +0000998 def help_EOF(self):
999 print """EOF
1000Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001001
Tim Peters2344fae2001-01-15 00:50:52 +00001002 def help_alias(self):
1003 print """alias [name [command [parameter parameter ...] ]]
1004Creates an alias called 'name' the executes 'command'. The command
1005must *not* be enclosed in quotes. Replaceable parameters are
1006indicated by %1, %2, and so on, while %* is replaced by all the
1007parameters. If no command is given, the current alias for name
1008is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +00001009
Tim Peters2344fae2001-01-15 00:50:52 +00001010Aliases may be nested and can contain anything that can be
1011legally typed at the pdb prompt. Note! You *can* override
1012internal pdb commands with aliases! Those internal commands
1013are then hidden until the alias is removed. Aliasing is recursively
1014applied to the first word of the command line; all other words
1015in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +00001016
Tim Peters2344fae2001-01-15 00:50:52 +00001017Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +00001018
Tim Peters2344fae2001-01-15 00:50:52 +00001019#Print instance variables (usage "pi classInst")
1020alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +00001021
Tim Peters2344fae2001-01-15 00:50:52 +00001022#Print instance variables in self
1023alias ps pi self
1024"""
Guido van Rossum2424f851998-09-11 22:50:09 +00001025
Tim Peters2344fae2001-01-15 00:50:52 +00001026 def help_unalias(self):
1027 print """unalias name
1028Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001029
Martin v. Löwisbd30f522006-04-17 17:08:37 +00001030 def help_commands(self):
1031 print """commands [bpnumber]
1032(com) ...
1033(com) end
1034(Pdb)
1035
1036Specify a list of commands for breakpoint number bpnumber. The
1037commands themselves appear on the following lines. Type a line
1038containing just 'end' to terminate the commands.
1039
1040To remove all commands from a breakpoint, type commands and
1041follow it immediately with end; that is, give no commands.
1042
1043With no bpnumber argument, commands refers to the last
1044breakpoint set.
1045
1046You can use breakpoint commands to start your program up again.
1047Simply use the continue command, or step, or any other
1048command that resumes execution.
1049
1050Specifying any command resuming execution (currently continue,
1051step, next, return, jump, quit and their abbreviations) terminates
1052the command list (as if that command was immediately followed by end).
1053This is because any time you resume execution
Martin v. Löwisf62eee12006-04-17 17:37:09 +00001054(even with a simple next or step), you may encounter
Martin v. Löwisbd30f522006-04-17 17:08:37 +00001055another breakpoint--which could have its own command list, leading to
1056ambiguities about which list to execute.
1057
1058 If you use the 'silent' command in the command list, the
1059usual message about stopping at a breakpoint is not printed. This may
1060be desirable for breakpoints that are to print a specific message and
1061then continue. If none of the other commands print anything, you
1062see no sign that the breakpoint was reached.
1063"""
1064
Tim Peters2344fae2001-01-15 00:50:52 +00001065 def help_pdb(self):
1066 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001067
Tim Peters2344fae2001-01-15 00:50:52 +00001068 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001069 """Helper function for break/clear parsing -- may be overridden.
1070
1071 lookupmodule() translates (possibly incomplete) file or module name
1072 into an absolute file name.
1073 """
1074 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001075 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001076 f = os.path.join(sys.path[0], filename)
1077 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1078 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001079 root, ext = os.path.splitext(filename)
1080 if ext == '':
1081 filename = filename + '.py'
1082 if os.path.isabs(filename):
1083 return filename
1084 for dirname in sys.path:
1085 while os.path.islink(dirname):
1086 dirname = os.readlink(dirname)
1087 fullname = os.path.join(dirname, filename)
1088 if os.path.exists(fullname):
1089 return fullname
1090 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001091
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001092 def _runscript(self, filename):
1093 # Start with fresh empty copy of globals and locals and tell the script
1094 # that it's being run as __main__ to avoid scripts being able to access
1095 # the pdb.py namespace.
Tim Peterse718f612004-10-12 21:51:32 +00001096 globals_ = {"__name__" : "__main__"}
1097 locals_ = globals_
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001098
1099 # When bdb sets tracing, a number of call and line events happens
1100 # BEFORE debugger even reaches user's code (and the exact sequence of
1101 # events depends on python version). So we take special measures to
1102 # avoid stopping before we reach the main script (see user_line and
1103 # user_call for details).
1104 self._wait_for_mainpyfile = 1
1105 self.mainpyfile = self.canonic(filename)
1106 self._user_requested_quit = 0
1107 statement = 'execfile( "%s")' % filename
1108 self.run(statement, globals=globals_, locals=locals_)
1109
Guido van Rossum35771131992-09-08 11:59:04 +00001110# Simplified interface
1111
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001112def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001113 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001114
1115def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001116 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001117
1118def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001119 # B/W compatibility
1120 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001121
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001122def runcall(*args, **kwds):
1123 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001124
Guido van Rossumb6775db1994-08-01 11:34:53 +00001125def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001126 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001127
1128# Post-Mortem interface
1129
1130def post_mortem(t):
Tim Peters2344fae2001-01-15 00:50:52 +00001131 p = Pdb()
1132 p.reset()
1133 while t.tb_next is not None:
1134 t = t.tb_next
1135 p.interaction(t.tb_frame, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001136
1137def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001138 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001139
1140
1141# Main program for testing
1142
Guido van Rossum23efba41992-01-27 16:58:47 +00001143TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001144
Guido van Rossum921c8241992-01-10 14:54:42 +00001145def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001146 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001147
1148# print help
1149def help():
Tim Peters2344fae2001-01-15 00:50:52 +00001150 for dirname in sys.path:
1151 fullname = os.path.join(dirname, 'pdb.doc')
1152 if os.path.exists(fullname):
1153 sts = os.system('${PAGER-more} '+fullname)
1154 if sts: print '*** Pager exit status:', sts
1155 break
1156 else:
1157 print 'Sorry, can\'t find the help file "pdb.doc"',
1158 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +00001159
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001160def main():
Tim Peters2344fae2001-01-15 00:50:52 +00001161 if not sys.argv[1:]:
1162 print "usage: pdb.py scriptfile [arg] ..."
1163 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001164
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001165 mainpyfile = sys.argv[1] # Get script filename
1166 if not os.path.exists(mainpyfile):
1167 print 'Error:', mainpyfile, 'does not exist'
Tim Peters2344fae2001-01-15 00:50:52 +00001168 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001169
Tim Peters2344fae2001-01-15 00:50:52 +00001170 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001171
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001172 # Replace pdb's dir with script's dir in front of module search path.
1173 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001174
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001175 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1176 # modified by the script being debugged. It's a bad idea when it was
1177 # changed by the user from the command line. The best approach would be to
1178 # have a "restart" command which would allow explicit specification of
1179 # command line arguments.
1180 pdb = Pdb()
1181 while 1:
1182 try:
1183 pdb._runscript(mainpyfile)
1184 if pdb._user_requested_quit:
1185 break
Tim Peterse718f612004-10-12 21:51:32 +00001186 print "The program finished and will be restarted"
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001187 except SystemExit:
1188 # In most cases SystemExit does not warrant a post-mortem session.
1189 print "The program exited via sys.exit(). Exit status: ",
1190 print sys.exc_info()[1]
1191 except:
1192 traceback.print_exc()
1193 print "Uncaught exception. Entering post mortem debugging"
1194 print "Running 'cont' or 'step' will restart the program"
1195 t = sys.exc_info()[2]
1196 while t.tb_next is not None:
1197 t = t.tb_next
1198 pdb.interaction(t.tb_frame,t)
1199 print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
1200
1201
1202# When invoked as main program, invoke the debugger on a script
1203if __name__=='__main__':
1204 main()