blob: 5b7ea998cdd583bd4a5fea495eabe2bec694df05 [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
Neal Norwitzce96f692006-03-17 06:49:51 +000025def raw_input(prompt):
26 sys.stdout.write(prompt)
27 sys.stdout.flush()
28 return sys.stdin.readline()
29
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000030def find_function(funcname, filename):
Tim Peters2344fae2001-01-15 00:50:52 +000031 cre = re.compile(r'def\s+%s\s*[(]' % funcname)
32 try:
33 fp = open(filename)
34 except IOError:
35 return None
36 # consumer of this info expects the first line to be 1
37 lineno = 1
38 answer = None
39 while 1:
40 line = fp.readline()
41 if line == '':
42 break
43 if cre.match(line):
44 answer = funcname, filename, lineno
45 break
46 lineno = lineno + 1
47 fp.close()
48 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +000049
50
Guido van Rossuma558e371994-11-10 22:27:35 +000051# Interaction prompt line will separate file and call info from code
52# text using value of line_prefix string. A newline and arrow may
53# be to your liking. You can set it once pdb is imported using the
54# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +000055# line_prefix = ': ' # Use this to get the old situation back
56line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +000057
Guido van Rossum23efba41992-01-27 16:58:47 +000058class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +000059
Tim Peters2344fae2001-01-15 00:50:52 +000060 def __init__(self):
61 bdb.Bdb.__init__(self)
62 cmd.Cmd.__init__(self)
63 self.prompt = '(Pdb) '
64 self.aliases = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +000065 self.mainpyfile = ''
66 self._wait_for_mainpyfile = 0
Tim Peters2344fae2001-01-15 00:50:52 +000067 # Try to load readline if it exists
68 try:
69 import readline
70 except ImportError:
71 pass
Guido van Rossum2424f851998-09-11 22:50:09 +000072
Tim Peters2344fae2001-01-15 00:50:52 +000073 # Read $HOME/.pdbrc and ./.pdbrc
74 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +000075 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +000076 envHome = os.environ['HOME']
77 try:
78 rcFile = open(os.path.join(envHome, ".pdbrc"))
79 except IOError:
80 pass
81 else:
82 for line in rcFile.readlines():
83 self.rcLines.append(line)
84 rcFile.close()
85 try:
86 rcFile = open(".pdbrc")
87 except IOError:
88 pass
89 else:
90 for line in rcFile.readlines():
91 self.rcLines.append(line)
92 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +000093
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000094 self.commands = {} # associates a command list to breakpoint numbers
95 self.commands_doprompt = {} # for each bp num, tells if the prompt must be disp. after execing the cmd list
96 self.commands_silent = {} # for each bp num, tells if the stack trace must be disp. after execing the cmd list
97 self.commands_defining = False # True while in the process of defining a command list
98 self.commands_bnum = None # The breakpoint number for which we are defining a list
99
Tim Peters2344fae2001-01-15 00:50:52 +0000100 def reset(self):
101 bdb.Bdb.reset(self)
102 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000103
Tim Peters2344fae2001-01-15 00:50:52 +0000104 def forget(self):
105 self.lineno = None
106 self.stack = []
107 self.curindex = 0
108 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +0000109
Tim Peters2344fae2001-01-15 00:50:52 +0000110 def setup(self, f, t):
111 self.forget()
112 self.stack, self.curindex = self.get_stack(f, t)
113 self.curframe = self.stack[self.curindex][0]
114 self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000115
Tim Peters2344fae2001-01-15 00:50:52 +0000116 # Can be executed earlier than 'setup' if desired
117 def execRcLines(self):
118 if self.rcLines:
119 # Make local copy because of recursion
120 rcLines = self.rcLines
121 # executed only once
122 self.rcLines = []
123 for line in rcLines:
124 line = line[:-1]
Guido van Rossum08454592002-07-12 13:10:53 +0000125 if len(line) > 0 and line[0] != '#':
126 self.onecmd(line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000127
Tim Peters280488b2002-08-23 18:19:30 +0000128 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000129
130 def user_call(self, frame, argument_list):
131 """This method is called when there is the remote possibility
132 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000133 if self._wait_for_mainpyfile:
134 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000135 if self.stop_here(frame):
136 print '--Call--'
137 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000138
Tim Peters2344fae2001-01-15 00:50:52 +0000139 def user_line(self, frame):
140 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000141 if self._wait_for_mainpyfile:
142 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
143 or frame.f_lineno<= 0):
144 return
145 self._wait_for_mainpyfile = 0
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000146 if self.bp_commands(frame):
147 self.interaction(frame, None)
148
149 def bp_commands(self,frame):
150 """ Call every command that was set for the current active breakpoint (if there is one)
151 Returns True if the normal interaction function must be called, False otherwise """
152 #self.currentbp is set in bdb.py in bdb.break_here if a breakpoint was hit
153 if getattr(self,"currentbp",False) and self.currentbp in self.commands:
154 currentbp = self.currentbp
155 self.currentbp = 0
156 lastcmd_back = self.lastcmd
157 self.setup(frame, None)
158 for line in self.commands[currentbp]:
159 self.onecmd(line)
160 self.lastcmd = lastcmd_back
161 if not self.commands_silent[currentbp]:
162 self.print_stack_entry(self.stack[self.curindex])
163 if self.commands_doprompt[currentbp]:
164 self.cmdloop()
165 self.forget()
166 return
167 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000168
Tim Peters2344fae2001-01-15 00:50:52 +0000169 def user_return(self, frame, return_value):
170 """This function is called when a return trap is set here."""
171 frame.f_locals['__return__'] = return_value
172 print '--Return--'
173 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000174
Tim Peters2344fae2001-01-15 00:50:52 +0000175 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
176 """This function is called if an exception occurs,
177 but only if we are to stop at or just below this level."""
178 frame.f_locals['__exception__'] = exc_type, exc_value
179 if type(exc_type) == type(''):
180 exc_type_name = exc_type
181 else: exc_type_name = exc_type.__name__
Tim Peters6f8ee592001-02-09 23:28:07 +0000182 print exc_type_name + ':', _saferepr(exc_value)
Tim Peters2344fae2001-01-15 00:50:52 +0000183 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000184
Tim Peters2344fae2001-01-15 00:50:52 +0000185 # General interaction function
186
187 def interaction(self, frame, traceback):
188 self.setup(frame, traceback)
189 self.print_stack_entry(self.stack[self.curindex])
190 self.cmdloop()
191 self.forget()
192
193 def default(self, line):
194 if line[:1] == '!': line = line[1:]
195 locals = self.curframe.f_locals
196 globals = self.curframe.f_globals
197 try:
198 code = compile(line + '\n', '<stdin>', 'single')
199 exec code in globals, locals
200 except:
201 t, v = sys.exc_info()[:2]
202 if type(t) == type(''):
203 exc_type_name = t
204 else: exc_type_name = t.__name__
205 print '***', exc_type_name + ':', v
206
207 def precmd(self, line):
208 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000209 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000210 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000211 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000212 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000213 line = self.aliases[args[0]]
214 ii = 1
215 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000216 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000217 tmpArg)
218 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000219 line = line.replace("%*", ' '.join(args[1:]))
220 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000221 # split into ';;' separated commands
222 # unless it's an alias command
223 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000224 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000225 if marker >= 0:
226 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000227 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000228 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000229 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000230 return line
231
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000232 def onecmd(self, line):
233 """Interpret the argument as though it had been typed in response
234 to the prompt.
235
236 Checks wether this line is typed in the normal prompt or in a breakpoint command list definition
237 """
238 if not self.commands_defining:
239 return cmd.Cmd.onecmd(self, line)
240 else:
241 return self.handle_command_def(line)
242
243 def handle_command_def(self,line):
244 """ Handles one command line during command list definition. """
245 cmd, arg, line = self.parseline(line)
246 if cmd == 'silent':
247 self.commands_silent[self.commands_bnum] = True
248 return # continue to handle other cmd def in the cmd list
249 elif cmd == 'end':
250 self.cmdqueue = []
251 return 1 # end of cmd list
252 cmdlist = self.commands[self.commands_bnum]
253 if (arg):
254 cmdlist.append(cmd+' '+arg)
255 else:
256 cmdlist.append(cmd)
257 # Determine if we must stop
258 try:
259 func = getattr(self, 'do_' + cmd)
260 except AttributeError:
261 func = self.default
262 if func.func_name in self.commands_resuming : # one of the resuming commands.
263 self.commands_doprompt[self.commands_bnum] = False
264 self.cmdqueue = []
265 return 1
266 return
267
Tim Peters2344fae2001-01-15 00:50:52 +0000268 # Command definitions, called by cmdloop()
269 # The argument is the remaining string on the command line
270 # Return true to exit from the command loop
271
272 do_h = cmd.Cmd.do_help
273
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000274 def do_commands(self, arg):
275 """Defines a list of commands associated to a breakpoint
276 Those commands will be executed whenever the breakpoint causes the program to stop execution."""
277 if not arg:
278 bnum = len(bdb.Breakpoint.bpbynumber)-1
279 else:
280 try:
281 bnum = int(arg)
282 except:
283 print "Usage : commands [bnum]\n ...\n end"
284 return
285 self.commands_bnum = bnum
286 self.commands[bnum] = []
287 self.commands_doprompt[bnum] = True
288 self.commands_silent[bnum] = False
289 prompt_back = self.prompt
290 self.prompt = '(com) '
291 self.commands_defining = True
292 self.cmdloop()
293 self.commands_defining = False
294 self.prompt = prompt_back
295
Tim Peters2344fae2001-01-15 00:50:52 +0000296 def do_break(self, arg, temporary = 0):
297 # break [ ([filename:]lineno | function) [, "condition"] ]
298 if not arg:
299 if self.breaks: # There's at least one
300 print "Num Type Disp Enb Where"
301 for bp in bdb.Breakpoint.bpbynumber:
302 if bp:
303 bp.bpprint()
304 return
305 # parse arguments; comma has lowest precedence
306 # and cannot occur in filename
307 filename = None
308 lineno = None
309 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000310 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000311 if comma > 0:
312 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000313 cond = arg[comma+1:].lstrip()
314 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000315 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000316 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000317 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000318 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000319 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000320 f = self.lookupmodule(filename)
321 if not f:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000322 print '*** ', repr(filename),
Tim Peters2344fae2001-01-15 00:50:52 +0000323 print 'not found from sys.path'
324 return
325 else:
326 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000327 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000328 try:
329 lineno = int(arg)
330 except ValueError, msg:
331 print '*** Bad lineno:', arg
332 return
333 else:
334 # no colon; can be lineno or function
335 try:
336 lineno = int(arg)
337 except ValueError:
338 try:
339 func = eval(arg,
340 self.curframe.f_globals,
341 self.curframe.f_locals)
342 except:
343 func = arg
344 try:
345 if hasattr(func, 'im_func'):
346 func = func.im_func
347 code = func.func_code
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000348 #use co_name to identify the bkpt (function names
349 #could be aliased, but co_name is invariant)
350 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000351 lineno = code.co_firstlineno
352 filename = code.co_filename
353 except:
354 # last thing to try
355 (ok, filename, ln) = self.lineinfo(arg)
356 if not ok:
357 print '*** The specified object',
Walter Dörwald70a6b492004-02-12 17:35:32 +0000358 print repr(arg),
Tim Peters2344fae2001-01-15 00:50:52 +0000359 print 'is not a function'
360 print ('or was not found '
361 'along sys.path.')
362 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000363 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000364 lineno = int(ln)
365 if not filename:
366 filename = self.defaultFile()
367 # Check for reasonable breakpoint
368 line = self.checkline(filename, lineno)
369 if line:
370 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000371 err = self.set_break(filename, line, temporary, cond, funcname)
Tim Peters2344fae2001-01-15 00:50:52 +0000372 if err: print '***', err
373 else:
374 bp = self.get_breaks(filename, line)[-1]
375 print "Breakpoint %d at %s:%d" % (bp.number,
376 bp.file,
377 bp.line)
378
379 # To be overridden in derived debuggers
380 def defaultFile(self):
381 """Produce a reasonable default."""
382 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000383 if filename == '<string>' and self.mainpyfile:
384 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000385 return filename
386
387 do_b = do_break
388
389 def do_tbreak(self, arg):
390 self.do_break(arg, 1)
391
392 def lineinfo(self, identifier):
393 failed = (None, None, None)
394 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000395 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000396 if len(idstring) == 1:
397 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000398 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000399 elif len(idstring) == 3:
400 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000401 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000402 else:
403 return failed
404 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000405 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000406 # Protection for derived debuggers
407 if parts[0] == 'self':
408 del parts[0]
409 if len(parts) == 0:
410 return failed
411 # Best first guess at file to look at
412 fname = self.defaultFile()
413 if len(parts) == 1:
414 item = parts[0]
415 else:
416 # More than one part.
417 # First is module, second is method/class
418 f = self.lookupmodule(parts[0])
419 if f:
420 fname = f
421 item = parts[1]
422 answer = find_function(item, fname)
423 return answer or failed
424
425 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000426 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000427
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000428 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
429 line or EOF). Warning: testing is not comprehensive.
430 """
Tim Peters2344fae2001-01-15 00:50:52 +0000431 line = linecache.getline(filename, lineno)
432 if not line:
433 print 'End of file'
434 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000435 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000436 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000437 if (not line or (line[0] == '#') or
438 (line[:3] == '"""') or line[:3] == "'''"):
Tim Peters2344fae2001-01-15 00:50:52 +0000439 print '*** Blank or comment'
440 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000441 return lineno
442
443 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000444 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000445 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000446 try:
447 i = int(i)
448 except ValueError:
449 print 'Breakpoint index %r is not a number' % i
450 continue
451
452 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
453 print 'No breakpoint numbered', i
454 continue
455
456 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000457 if bp:
458 bp.enable()
459
460 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000461 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000462 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000463 try:
464 i = int(i)
465 except ValueError:
466 print 'Breakpoint index %r is not a number' % i
467 continue
Tim Petersf545baa2003-06-15 23:26:30 +0000468
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000469 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
470 print 'No breakpoint numbered', i
471 continue
472
473 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000474 if bp:
475 bp.disable()
476
477 def do_condition(self, arg):
478 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000479 args = arg.split(' ', 1)
480 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000481 try:
482 cond = args[1]
483 except:
484 cond = None
485 bp = bdb.Breakpoint.bpbynumber[bpnum]
486 if bp:
487 bp.cond = cond
488 if not cond:
489 print 'Breakpoint', bpnum,
490 print 'is now unconditional.'
491
492 def do_ignore(self,arg):
493 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000494 args = arg.split()
495 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000496 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000497 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000498 except:
499 count = 0
500 bp = bdb.Breakpoint.bpbynumber[bpnum]
501 if bp:
502 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000503 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000504 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000505 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000506 reply = reply + '%d crossings' % count
507 else:
508 reply = reply + '1 crossing'
509 print reply + ' of breakpoint %d.' % bpnum
510 else:
511 print 'Will stop next time breakpoint',
512 print bpnum, 'is reached.'
513
514 def do_clear(self, arg):
515 """Three possibilities, tried in this order:
516 clear -> clear all breaks, ask for confirmation
517 clear file:lineno -> clear all breaks at file:lineno
518 clear bpno bpno ... -> clear breakpoints by number"""
519 if not arg:
520 try:
521 reply = raw_input('Clear all breaks? ')
522 except EOFError:
523 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000524 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000525 if reply in ('y', 'yes'):
526 self.clear_all_breaks()
527 return
528 if ':' in arg:
529 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000530 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000531 filename = arg[:i]
532 arg = arg[i+1:]
533 try:
534 lineno = int(arg)
535 except:
536 err = "Invalid line number (%s)" % arg
537 else:
538 err = self.clear_break(filename, lineno)
539 if err: print '***', err
540 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000541 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000542 for i in numberlist:
Georg Brandl6d2b3462005-08-24 07:36:17 +0000543 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
544 print 'No breakpoint numbered', i
545 continue
Tim Peters2344fae2001-01-15 00:50:52 +0000546 err = self.clear_bpbynumber(i)
547 if err:
548 print '***', err
549 else:
Georg Brandl6d2b3462005-08-24 07:36:17 +0000550 print 'Deleted breakpoint', i
Tim Peters2344fae2001-01-15 00:50:52 +0000551 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
552
553 def do_where(self, arg):
554 self.print_stack_trace()
555 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000556 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000557
558 def do_up(self, arg):
559 if self.curindex == 0:
560 print '*** Oldest frame'
561 else:
562 self.curindex = self.curindex - 1
563 self.curframe = self.stack[self.curindex][0]
564 self.print_stack_entry(self.stack[self.curindex])
565 self.lineno = None
566 do_u = do_up
567
568 def do_down(self, arg):
569 if self.curindex + 1 == len(self.stack):
570 print '*** Newest frame'
571 else:
572 self.curindex = self.curindex + 1
573 self.curframe = self.stack[self.curindex][0]
574 self.print_stack_entry(self.stack[self.curindex])
575 self.lineno = None
576 do_d = do_down
577
578 def do_step(self, arg):
579 self.set_step()
580 return 1
581 do_s = do_step
582
583 def do_next(self, arg):
584 self.set_next(self.curframe)
585 return 1
586 do_n = do_next
587
588 def do_return(self, arg):
589 self.set_return(self.curframe)
590 return 1
591 do_r = do_return
592
593 def do_continue(self, arg):
594 self.set_continue()
595 return 1
596 do_c = do_cont = do_continue
597
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000598 def do_jump(self, arg):
599 if self.curindex + 1 != len(self.stack):
600 print "*** You can only jump within the bottom frame"
601 return
602 try:
603 arg = int(arg)
604 except ValueError:
605 print "*** The 'jump' command requires a line number."
606 else:
607 try:
608 # Do the jump, fix up our copy of the stack, and display the
609 # new position
610 self.curframe.f_lineno = arg
611 self.stack[self.curindex] = self.stack[self.curindex][0], arg
612 self.print_stack_entry(self.stack[self.curindex])
613 except ValueError, e:
614 print '*** Jump failed:', e
615 do_j = do_jump
616
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000617 def do_debug(self, arg):
618 sys.settrace(None)
619 globals = self.curframe.f_globals
620 locals = self.curframe.f_locals
Guido van Rossumed538d82003-04-09 19:36:34 +0000621 p = Pdb()
622 p.prompt = "(%s) " % self.prompt.strip()
623 print "ENTERING RECURSIVE DEBUGGER"
624 sys.call_tracing(p.run, (arg, globals, locals))
625 print "LEAVING RECURSIVE DEBUGGER"
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000626 sys.settrace(self.trace_dispatch)
627 self.lastcmd = p.lastcmd
628
Tim Peters2344fae2001-01-15 00:50:52 +0000629 def do_quit(self, arg):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000630 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000631 self.set_quit()
632 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000633
Tim Peters2344fae2001-01-15 00:50:52 +0000634 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000635 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000636
Guido van Rossumeef26072003-01-13 21:13:55 +0000637 def do_EOF(self, arg):
638 print
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000639 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000640 self.set_quit()
641 return 1
642
Tim Peters2344fae2001-01-15 00:50:52 +0000643 def do_args(self, arg):
644 f = self.curframe
645 co = f.f_code
646 dict = f.f_locals
647 n = co.co_argcount
648 if co.co_flags & 4: n = n+1
649 if co.co_flags & 8: n = n+1
650 for i in range(n):
651 name = co.co_varnames[i]
652 print name, '=',
Raymond Hettinger54f02222002-06-01 14:18:47 +0000653 if name in dict: print dict[name]
Tim Peters2344fae2001-01-15 00:50:52 +0000654 else: print "*** undefined ***"
655 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000656
Tim Peters2344fae2001-01-15 00:50:52 +0000657 def do_retval(self, arg):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000658 if '__return__' in self.curframe.f_locals:
Tim Peters2344fae2001-01-15 00:50:52 +0000659 print self.curframe.f_locals['__return__']
660 else:
661 print '*** Not yet returned!'
662 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000663
Barry Warsaw210bd202002-11-05 22:40:20 +0000664 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000665 try:
Barry Warsaw210bd202002-11-05 22:40:20 +0000666 return eval(arg, self.curframe.f_globals,
667 self.curframe.f_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000668 except:
669 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000670 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000671 exc_type_name = t
672 else: exc_type_name = t.__name__
Walter Dörwald70a6b492004-02-12 17:35:32 +0000673 print '***', exc_type_name + ':', repr(v)
Barry Warsaw210bd202002-11-05 22:40:20 +0000674 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000675
Barry Warsaw210bd202002-11-05 22:40:20 +0000676 def do_p(self, arg):
677 try:
678 print repr(self._getval(arg))
679 except:
680 pass
681
682 def do_pp(self, arg):
683 try:
684 pprint.pprint(self._getval(arg))
685 except:
686 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000687
Tim Peters2344fae2001-01-15 00:50:52 +0000688 def do_list(self, arg):
689 self.lastcmd = 'list'
690 last = None
691 if arg:
692 try:
693 x = eval(arg, {}, {})
694 if type(x) == type(()):
695 first, last = x
696 first = int(first)
697 last = int(last)
698 if last < first:
699 # Assume it's a count
700 last = first + last
701 else:
702 first = max(1, int(x) - 5)
703 except:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000704 print '*** Error in argument:', repr(arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000705 return
706 elif self.lineno is None:
707 first = max(1, self.curframe.f_lineno - 5)
708 else:
709 first = self.lineno + 1
710 if last is None:
711 last = first + 10
712 filename = self.curframe.f_code.co_filename
713 breaklist = self.get_file_breaks(filename)
714 try:
715 for lineno in range(first, last+1):
716 line = linecache.getline(filename, lineno)
717 if not line:
718 print '[EOF]'
719 break
720 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000721 s = repr(lineno).rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000722 if len(s) < 4: s = s + ' '
723 if lineno in breaklist: s = s + 'B'
724 else: s = s + ' '
725 if lineno == self.curframe.f_lineno:
726 s = s + '->'
727 print s + '\t' + line,
728 self.lineno = lineno
729 except KeyboardInterrupt:
730 pass
731 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000732
Tim Peters2344fae2001-01-15 00:50:52 +0000733 def do_whatis(self, arg):
734 try:
735 value = eval(arg, self.curframe.f_globals,
736 self.curframe.f_locals)
737 except:
738 t, v = sys.exc_info()[:2]
739 if type(t) == type(''):
740 exc_type_name = t
741 else: exc_type_name = t.__name__
Walter Dörwald70a6b492004-02-12 17:35:32 +0000742 print '***', exc_type_name + ':', repr(v)
Tim Peters2344fae2001-01-15 00:50:52 +0000743 return
744 code = None
745 # Is it a function?
746 try: code = value.func_code
747 except: pass
748 if code:
749 print 'Function', code.co_name
750 return
751 # Is it an instance method?
752 try: code = value.im_func.func_code
753 except: pass
754 if code:
755 print 'Method', code.co_name
756 return
757 # None of the above...
758 print type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000759
Tim Peters2344fae2001-01-15 00:50:52 +0000760 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000761 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000762 if len(args) == 0:
763 keys = self.aliases.keys()
764 keys.sort()
765 for alias in keys:
766 print "%s = %s" % (alias, self.aliases[alias])
767 return
Guido van Rossum08454592002-07-12 13:10:53 +0000768 if args[0] in self.aliases and len(args) == 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000769 print "%s = %s" % (args[0], self.aliases[args[0]])
770 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000771 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000772
Tim Peters2344fae2001-01-15 00:50:52 +0000773 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000774 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000775 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000776 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000777 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000778
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000779 #list of all the commands making the program resume execution.
780 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return', 'do_quit', 'do_jump']
781
Tim Peters2344fae2001-01-15 00:50:52 +0000782 # Print a traceback starting at the top stack frame.
783 # The most recently entered frame is printed last;
784 # this is different from dbx and gdb, but consistent with
785 # the Python interpreter's stack trace.
786 # It is also consistent with the up/down commands (which are
787 # compatible with dbx and gdb: up moves towards 'main()'
788 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000789
Tim Peters2344fae2001-01-15 00:50:52 +0000790 def print_stack_trace(self):
791 try:
792 for frame_lineno in self.stack:
793 self.print_stack_entry(frame_lineno)
794 except KeyboardInterrupt:
795 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000796
Tim Peters2344fae2001-01-15 00:50:52 +0000797 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
798 frame, lineno = frame_lineno
799 if frame is self.curframe:
800 print '>',
801 else:
802 print ' ',
803 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000804
Guido van Rossum921c8241992-01-10 14:54:42 +0000805
Tim Peters2344fae2001-01-15 00:50:52 +0000806 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000807
Tim Peters2344fae2001-01-15 00:50:52 +0000808 def help_help(self):
809 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000810
Tim Peters2344fae2001-01-15 00:50:52 +0000811 def help_h(self):
812 print """h(elp)
813Without argument, print the list of available commands.
814With a command name as argument, print help about that command
815"help pdb" pipes the full documentation file to the $PAGER
816"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000817
Tim Peters2344fae2001-01-15 00:50:52 +0000818 def help_where(self):
819 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000820
Tim Peters2344fae2001-01-15 00:50:52 +0000821 def help_w(self):
822 print """w(here)
823Print a stack trace, with the most recent frame at the bottom.
824An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000825context of most commands. 'bt' is an alias for this command."""
826
827 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000828
Tim Peters2344fae2001-01-15 00:50:52 +0000829 def help_down(self):
830 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000831
Tim Peters2344fae2001-01-15 00:50:52 +0000832 def help_d(self):
833 print """d(own)
834Move the current frame one level down in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000835(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000836
Tim Peters2344fae2001-01-15 00:50:52 +0000837 def help_up(self):
838 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000839
Tim Peters2344fae2001-01-15 00:50:52 +0000840 def help_u(self):
841 print """u(p)
842Move the current frame one level up in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000843(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000844
Tim Peters2344fae2001-01-15 00:50:52 +0000845 def help_break(self):
846 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000847
Tim Peters2344fae2001-01-15 00:50:52 +0000848 def help_b(self):
849 print """b(reak) ([file:]lineno | function) [, condition]
850With a line number argument, set a break there in the current
851file. With a function name, set a break at first executable line
852of that function. Without argument, list all breaks. If a second
853argument is present, it is a string specifying an expression
854which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000855
Tim Peters2344fae2001-01-15 00:50:52 +0000856The line number may be prefixed with a filename and a colon,
857to specify a breakpoint in another file (probably one that
858hasn't been loaded yet). The file is searched for on sys.path;
859the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000860
Tim Peters2344fae2001-01-15 00:50:52 +0000861 def help_clear(self):
862 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000863
Tim Peters2344fae2001-01-15 00:50:52 +0000864 def help_cl(self):
865 print "cl(ear) filename:lineno"
866 print """cl(ear) [bpnumber [bpnumber...]]
867With a space separated list of breakpoint numbers, clear
868those breakpoints. Without argument, clear all breaks (but
869first ask confirmation). With a filename:lineno argument,
870clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000871
Tim Peters2344fae2001-01-15 00:50:52 +0000872Note that the argument is different from previous versions of
873the debugger (in python distributions 1.5.1 and before) where
874a linenumber was used instead of either filename:lineno or
875breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000876
Tim Peters2344fae2001-01-15 00:50:52 +0000877 def help_tbreak(self):
878 print """tbreak same arguments as break, but breakpoint is
879removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000880
Tim Peters2344fae2001-01-15 00:50:52 +0000881 def help_enable(self):
882 print """enable bpnumber [bpnumber ...]
883Enables 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_disable(self):
887 print """disable bpnumber [bpnumber ...]
888Disables the breakpoints given as a space separated list of
889bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000890
Tim Peters2344fae2001-01-15 00:50:52 +0000891 def help_ignore(self):
892 print """ignore bpnumber count
893Sets the ignore count for the given breakpoint number. A breakpoint
894becomes active when the ignore count is zero. When non-zero, the
895count is decremented each time the breakpoint is reached and the
896breakpoint is not disabled and any associated condition evaluates
897to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000898
Tim Peters2344fae2001-01-15 00:50:52 +0000899 def help_condition(self):
900 print """condition bpnumber str_condition
901str_condition is a string specifying an expression which
902must evaluate to true before the breakpoint is honored.
903If str_condition is absent, any existing condition is removed;
904i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000905
Tim Peters2344fae2001-01-15 00:50:52 +0000906 def help_step(self):
907 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000908
Tim Peters2344fae2001-01-15 00:50:52 +0000909 def help_s(self):
910 print """s(tep)
911Execute the current line, stop at the first possible occasion
912(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000913
Tim Peters2344fae2001-01-15 00:50:52 +0000914 def help_next(self):
915 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000916
Tim Peters2344fae2001-01-15 00:50:52 +0000917 def help_n(self):
918 print """n(ext)
919Continue execution until the next line in the current function
920is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000921
Tim Peters2344fae2001-01-15 00:50:52 +0000922 def help_return(self):
923 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000924
Tim Peters2344fae2001-01-15 00:50:52 +0000925 def help_r(self):
926 print """r(eturn)
927Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000928
Tim Peters2344fae2001-01-15 00:50:52 +0000929 def help_continue(self):
930 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000931
Tim Peters2344fae2001-01-15 00:50:52 +0000932 def help_cont(self):
933 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000934
Tim Peters2344fae2001-01-15 00:50:52 +0000935 def help_c(self):
936 print """c(ont(inue))
937Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000938
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000939 def help_jump(self):
940 self.help_j()
941
942 def help_j(self):
943 print """j(ump) lineno
944Set the next line that will be executed."""
945
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000946 def help_debug(self):
947 print """debug code
948Enter a recursive debugger that steps through the code argument
949(which is an arbitrary expression or statement to be executed
950in the current environment)."""
951
Tim Peters2344fae2001-01-15 00:50:52 +0000952 def help_list(self):
953 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000954
Tim Peters2344fae2001-01-15 00:50:52 +0000955 def help_l(self):
956 print """l(ist) [first [,last]]
957List source code for the current file.
958Without arguments, list 11 lines around the current line
959or continue the previous listing.
960With one argument, list 11 lines starting at that line.
961With two arguments, list the given range;
962if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000963
Tim Peters2344fae2001-01-15 00:50:52 +0000964 def help_args(self):
965 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000966
Tim Peters2344fae2001-01-15 00:50:52 +0000967 def help_a(self):
968 print """a(rgs)
969Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000970
Tim Peters2344fae2001-01-15 00:50:52 +0000971 def help_p(self):
972 print """p expression
973Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000974
Barry Warsaw210bd202002-11-05 22:40:20 +0000975 def help_pp(self):
976 print """pp expression
977Pretty-print the value of the expression."""
978
Tim Peters2344fae2001-01-15 00:50:52 +0000979 def help_exec(self):
980 print """(!) statement
981Execute the (one-line) statement in the context of
982the current stack frame.
983The exclamation point can be omitted unless the first word
984of the statement resembles a debugger command.
985To assign to a global variable you must always prefix the
986command with a 'global' command, e.g.:
987(Pdb) global list_options; list_options = ['-l']
988(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000989
Tim Peters2344fae2001-01-15 00:50:52 +0000990 def help_quit(self):
991 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000992
Tim Peters2344fae2001-01-15 00:50:52 +0000993 def help_q(self):
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000994 print """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +0000995The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000996
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000997 help_exit = help_q
998
Tim Peters2344fae2001-01-15 00:50:52 +0000999 def help_whatis(self):
1000 print """whatis arg
1001Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001002
Tim Peters2344fae2001-01-15 00:50:52 +00001003 def help_EOF(self):
1004 print """EOF
1005Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001006
Tim Peters2344fae2001-01-15 00:50:52 +00001007 def help_alias(self):
1008 print """alias [name [command [parameter parameter ...] ]]
1009Creates an alias called 'name' the executes 'command'. The command
1010must *not* be enclosed in quotes. Replaceable parameters are
1011indicated by %1, %2, and so on, while %* is replaced by all the
1012parameters. If no command is given, the current alias for name
1013is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +00001014
Tim Peters2344fae2001-01-15 00:50:52 +00001015Aliases may be nested and can contain anything that can be
1016legally typed at the pdb prompt. Note! You *can* override
1017internal pdb commands with aliases! Those internal commands
1018are then hidden until the alias is removed. Aliasing is recursively
1019applied to the first word of the command line; all other words
1020in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +00001021
Tim Peters2344fae2001-01-15 00:50:52 +00001022Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +00001023
Tim Peters2344fae2001-01-15 00:50:52 +00001024#Print instance variables (usage "pi classInst")
1025alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +00001026
Tim Peters2344fae2001-01-15 00:50:52 +00001027#Print instance variables in self
1028alias ps pi self
1029"""
Guido van Rossum2424f851998-09-11 22:50:09 +00001030
Tim Peters2344fae2001-01-15 00:50:52 +00001031 def help_unalias(self):
1032 print """unalias name
1033Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001034
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001035 def help_commands(self):
1036 print """commands [bpnumber]
1037(com) ...
1038(com) end
1039(Pdb)
1040
1041Specify a list of commands for breakpoint number bpnumber. The
1042commands themselves appear on the following lines. Type a line
1043containing just 'end' to terminate the commands.
1044
1045To remove all commands from a breakpoint, type commands and
1046follow it immediately with end; that is, give no commands.
1047
1048With no bpnumber argument, commands refers to the last
1049breakpoint set.
1050
1051You can use breakpoint commands to start your program up again.
1052Simply use the continue command, or step, or any other
1053command that resumes execution.
1054
1055Specifying any command resuming execution (currently continue,
1056step, next, return, jump, quit and their abbreviations) terminates
1057the command list (as if that command was immediately followed by end).
1058This is because any time you resume execution
1059(even with a simple next or step), you may encounter
1060another breakpoint--which could have its own command list, leading to
1061ambiguities about which list to execute.
1062
1063 If you use the 'silent' command in the command list, the
1064usual message about stopping at a breakpoint is not printed. This may
1065be desirable for breakpoints that are to print a specific message and
1066then continue. If none of the other commands print anything, you
1067see no sign that the breakpoint was reached.
1068"""
1069
Tim Peters2344fae2001-01-15 00:50:52 +00001070 def help_pdb(self):
1071 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001072
Tim Peters2344fae2001-01-15 00:50:52 +00001073 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001074 """Helper function for break/clear parsing -- may be overridden.
1075
1076 lookupmodule() translates (possibly incomplete) file or module name
1077 into an absolute file name.
1078 """
1079 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001080 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001081 f = os.path.join(sys.path[0], filename)
1082 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1083 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001084 root, ext = os.path.splitext(filename)
1085 if ext == '':
1086 filename = filename + '.py'
1087 if os.path.isabs(filename):
1088 return filename
1089 for dirname in sys.path:
1090 while os.path.islink(dirname):
1091 dirname = os.readlink(dirname)
1092 fullname = os.path.join(dirname, filename)
1093 if os.path.exists(fullname):
1094 return fullname
1095 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001096
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001097 def _runscript(self, filename):
1098 # Start with fresh empty copy of globals and locals and tell the script
1099 # that it's being run as __main__ to avoid scripts being able to access
1100 # the pdb.py namespace.
Tim Peterse718f612004-10-12 21:51:32 +00001101 globals_ = {"__name__" : "__main__"}
1102 locals_ = globals_
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001103
1104 # When bdb sets tracing, a number of call and line events happens
1105 # BEFORE debugger even reaches user's code (and the exact sequence of
1106 # events depends on python version). So we take special measures to
1107 # avoid stopping before we reach the main script (see user_line and
1108 # user_call for details).
1109 self._wait_for_mainpyfile = 1
1110 self.mainpyfile = self.canonic(filename)
1111 self._user_requested_quit = 0
1112 statement = 'execfile( "%s")' % filename
1113 self.run(statement, globals=globals_, locals=locals_)
1114
Guido van Rossum35771131992-09-08 11:59:04 +00001115# Simplified interface
1116
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001117def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001118 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001119
1120def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001121 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001122
1123def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001124 # B/W compatibility
1125 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001126
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001127def runcall(*args, **kwds):
1128 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001129
Guido van Rossumb6775db1994-08-01 11:34:53 +00001130def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001131 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001132
1133# Post-Mortem interface
1134
1135def post_mortem(t):
Tim Peters2344fae2001-01-15 00:50:52 +00001136 p = Pdb()
1137 p.reset()
1138 while t.tb_next is not None:
1139 t = t.tb_next
1140 p.interaction(t.tb_frame, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001141
1142def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001143 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001144
1145
1146# Main program for testing
1147
Guido van Rossum23efba41992-01-27 16:58:47 +00001148TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001149
Guido van Rossum921c8241992-01-10 14:54:42 +00001150def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001151 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001152
1153# print help
1154def help():
Tim Peters2344fae2001-01-15 00:50:52 +00001155 for dirname in sys.path:
1156 fullname = os.path.join(dirname, 'pdb.doc')
1157 if os.path.exists(fullname):
1158 sts = os.system('${PAGER-more} '+fullname)
1159 if sts: print '*** Pager exit status:', sts
1160 break
1161 else:
1162 print 'Sorry, can\'t find the help file "pdb.doc"',
1163 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +00001164
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001165def main():
Tim Peters2344fae2001-01-15 00:50:52 +00001166 if not sys.argv[1:]:
1167 print "usage: pdb.py scriptfile [arg] ..."
1168 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001169
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001170 mainpyfile = sys.argv[1] # Get script filename
1171 if not os.path.exists(mainpyfile):
1172 print 'Error:', mainpyfile, 'does not exist'
Tim Peters2344fae2001-01-15 00:50:52 +00001173 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001174
Tim Peters2344fae2001-01-15 00:50:52 +00001175 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001176
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001177 # Replace pdb's dir with script's dir in front of module search path.
1178 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001179
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001180 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1181 # modified by the script being debugged. It's a bad idea when it was
1182 # changed by the user from the command line. The best approach would be to
1183 # have a "restart" command which would allow explicit specification of
1184 # command line arguments.
1185 pdb = Pdb()
1186 while 1:
1187 try:
1188 pdb._runscript(mainpyfile)
1189 if pdb._user_requested_quit:
1190 break
Tim Peterse718f612004-10-12 21:51:32 +00001191 print "The program finished and will be restarted"
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001192 except SystemExit:
1193 # In most cases SystemExit does not warrant a post-mortem session.
1194 print "The program exited via sys.exit(). Exit status: ",
1195 print sys.exc_info()[1]
1196 except:
1197 traceback.print_exc()
1198 print "Uncaught exception. Entering post mortem debugging"
1199 print "Running 'cont' or 'step' will restart the program"
1200 t = sys.exc_info()[2]
1201 while t.tb_next is not None:
1202 t = t.tb_next
1203 pdb.interaction(t.tb_frame,t)
1204 print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
1205
1206
1207# When invoked as main program, invoke the debugger on a script
1208if __name__=='__main__':
1209 main()