blob: 1aa2eaee2722e49cf4ee1d619f0751669c055855 [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
Tim Peters2344fae2001-01-15 00:50:52 +000094 def reset(self):
95 bdb.Bdb.reset(self)
96 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +000097
Tim Peters2344fae2001-01-15 00:50:52 +000098 def forget(self):
99 self.lineno = None
100 self.stack = []
101 self.curindex = 0
102 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +0000103
Tim Peters2344fae2001-01-15 00:50:52 +0000104 def setup(self, f, t):
105 self.forget()
106 self.stack, self.curindex = self.get_stack(f, t)
107 self.curframe = self.stack[self.curindex][0]
108 self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000109
Tim Peters2344fae2001-01-15 00:50:52 +0000110 # Can be executed earlier than 'setup' if desired
111 def execRcLines(self):
112 if self.rcLines:
113 # Make local copy because of recursion
114 rcLines = self.rcLines
115 # executed only once
116 self.rcLines = []
117 for line in rcLines:
118 line = line[:-1]
Guido van Rossum08454592002-07-12 13:10:53 +0000119 if len(line) > 0 and line[0] != '#':
120 self.onecmd(line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000121
Tim Peters280488b2002-08-23 18:19:30 +0000122 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000123
124 def user_call(self, frame, argument_list):
125 """This method is called when there is the remote possibility
126 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000127 if self._wait_for_mainpyfile:
128 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000129 if self.stop_here(frame):
130 print '--Call--'
131 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000132
Tim Peters2344fae2001-01-15 00:50:52 +0000133 def user_line(self, frame):
134 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000135 if self._wait_for_mainpyfile:
136 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
137 or frame.f_lineno<= 0):
138 return
139 self._wait_for_mainpyfile = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000140 self.interaction(frame, None)
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000141
Tim Peters2344fae2001-01-15 00:50:52 +0000142 def user_return(self, frame, return_value):
143 """This function is called when a return trap is set here."""
144 frame.f_locals['__return__'] = return_value
145 print '--Return--'
146 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000147
Tim Peters2344fae2001-01-15 00:50:52 +0000148 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
149 """This function is called if an exception occurs,
150 but only if we are to stop at or just below this level."""
151 frame.f_locals['__exception__'] = exc_type, exc_value
152 if type(exc_type) == type(''):
153 exc_type_name = exc_type
154 else: exc_type_name = exc_type.__name__
Tim Peters6f8ee592001-02-09 23:28:07 +0000155 print exc_type_name + ':', _saferepr(exc_value)
Tim Peters2344fae2001-01-15 00:50:52 +0000156 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000157
Tim Peters2344fae2001-01-15 00:50:52 +0000158 # General interaction function
159
160 def interaction(self, frame, traceback):
161 self.setup(frame, traceback)
162 self.print_stack_entry(self.stack[self.curindex])
163 self.cmdloop()
164 self.forget()
165
166 def default(self, line):
167 if line[:1] == '!': line = line[1:]
168 locals = self.curframe.f_locals
169 globals = self.curframe.f_globals
170 try:
171 code = compile(line + '\n', '<stdin>', 'single')
172 exec code in globals, locals
173 except:
174 t, v = sys.exc_info()[:2]
175 if type(t) == type(''):
176 exc_type_name = t
177 else: exc_type_name = t.__name__
178 print '***', exc_type_name + ':', v
179
180 def precmd(self, line):
181 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000182 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000183 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000184 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000185 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000186 line = self.aliases[args[0]]
187 ii = 1
188 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000189 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000190 tmpArg)
191 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000192 line = line.replace("%*", ' '.join(args[1:]))
193 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000194 # split into ';;' separated commands
195 # unless it's an alias command
196 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000197 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000198 if marker >= 0:
199 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000200 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000201 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000202 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000203 return line
204
205 # Command definitions, called by cmdloop()
206 # The argument is the remaining string on the command line
207 # Return true to exit from the command loop
208
209 do_h = cmd.Cmd.do_help
210
Tim Peters2344fae2001-01-15 00:50:52 +0000211 def do_break(self, arg, temporary = 0):
212 # break [ ([filename:]lineno | function) [, "condition"] ]
213 if not arg:
214 if self.breaks: # There's at least one
215 print "Num Type Disp Enb Where"
216 for bp in bdb.Breakpoint.bpbynumber:
217 if bp:
218 bp.bpprint()
219 return
220 # parse arguments; comma has lowest precedence
221 # and cannot occur in filename
222 filename = None
223 lineno = None
224 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000225 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000226 if comma > 0:
227 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000228 cond = arg[comma+1:].lstrip()
229 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000230 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000231 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000232 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000233 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000234 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000235 f = self.lookupmodule(filename)
236 if not f:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000237 print '*** ', repr(filename),
Tim Peters2344fae2001-01-15 00:50:52 +0000238 print 'not found from sys.path'
239 return
240 else:
241 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000242 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000243 try:
244 lineno = int(arg)
245 except ValueError, msg:
246 print '*** Bad lineno:', arg
247 return
248 else:
249 # no colon; can be lineno or function
250 try:
251 lineno = int(arg)
252 except ValueError:
253 try:
254 func = eval(arg,
255 self.curframe.f_globals,
256 self.curframe.f_locals)
257 except:
258 func = arg
259 try:
260 if hasattr(func, 'im_func'):
261 func = func.im_func
262 code = func.func_code
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000263 #use co_name to identify the bkpt (function names
264 #could be aliased, but co_name is invariant)
265 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000266 lineno = code.co_firstlineno
267 filename = code.co_filename
268 except:
269 # last thing to try
270 (ok, filename, ln) = self.lineinfo(arg)
271 if not ok:
272 print '*** The specified object',
Walter Dörwald70a6b492004-02-12 17:35:32 +0000273 print repr(arg),
Tim Peters2344fae2001-01-15 00:50:52 +0000274 print 'is not a function'
275 print ('or was not found '
276 'along sys.path.')
277 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000278 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000279 lineno = int(ln)
280 if not filename:
281 filename = self.defaultFile()
282 # Check for reasonable breakpoint
283 line = self.checkline(filename, lineno)
284 if line:
285 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000286 err = self.set_break(filename, line, temporary, cond, funcname)
Tim Peters2344fae2001-01-15 00:50:52 +0000287 if err: print '***', err
288 else:
289 bp = self.get_breaks(filename, line)[-1]
290 print "Breakpoint %d at %s:%d" % (bp.number,
291 bp.file,
292 bp.line)
293
294 # To be overridden in derived debuggers
295 def defaultFile(self):
296 """Produce a reasonable default."""
297 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000298 if filename == '<string>' and self.mainpyfile:
299 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000300 return filename
301
302 do_b = do_break
303
304 def do_tbreak(self, arg):
305 self.do_break(arg, 1)
306
307 def lineinfo(self, identifier):
308 failed = (None, None, None)
309 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000310 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000311 if len(idstring) == 1:
312 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000313 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000314 elif len(idstring) == 3:
315 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000316 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000317 else:
318 return failed
319 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000320 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000321 # Protection for derived debuggers
322 if parts[0] == 'self':
323 del parts[0]
324 if len(parts) == 0:
325 return failed
326 # Best first guess at file to look at
327 fname = self.defaultFile()
328 if len(parts) == 1:
329 item = parts[0]
330 else:
331 # More than one part.
332 # First is module, second is method/class
333 f = self.lookupmodule(parts[0])
334 if f:
335 fname = f
336 item = parts[1]
337 answer = find_function(item, fname)
338 return answer or failed
339
340 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000341 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000342
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000343 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
344 line or EOF). Warning: testing is not comprehensive.
345 """
Tim Peters2344fae2001-01-15 00:50:52 +0000346 line = linecache.getline(filename, lineno)
347 if not line:
348 print 'End of file'
349 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000350 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000351 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000352 if (not line or (line[0] == '#') or
353 (line[:3] == '"""') or line[:3] == "'''"):
Tim Peters2344fae2001-01-15 00:50:52 +0000354 print '*** Blank or comment'
355 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000356 return lineno
357
358 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000359 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000360 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000361 try:
362 i = int(i)
363 except ValueError:
364 print 'Breakpoint index %r is not a number' % i
365 continue
366
367 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
368 print 'No breakpoint numbered', i
369 continue
370
371 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000372 if bp:
373 bp.enable()
374
375 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000376 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000377 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000378 try:
379 i = int(i)
380 except ValueError:
381 print 'Breakpoint index %r is not a number' % i
382 continue
Tim Petersf545baa2003-06-15 23:26:30 +0000383
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000384 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
385 print 'No breakpoint numbered', i
386 continue
387
388 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000389 if bp:
390 bp.disable()
391
392 def do_condition(self, arg):
393 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000394 args = arg.split(' ', 1)
395 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000396 try:
397 cond = args[1]
398 except:
399 cond = None
400 bp = bdb.Breakpoint.bpbynumber[bpnum]
401 if bp:
402 bp.cond = cond
403 if not cond:
404 print 'Breakpoint', bpnum,
405 print 'is now unconditional.'
406
407 def do_ignore(self,arg):
408 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000409 args = arg.split()
410 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000411 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000412 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000413 except:
414 count = 0
415 bp = bdb.Breakpoint.bpbynumber[bpnum]
416 if bp:
417 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000418 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000419 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000420 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000421 reply = reply + '%d crossings' % count
422 else:
423 reply = reply + '1 crossing'
424 print reply + ' of breakpoint %d.' % bpnum
425 else:
426 print 'Will stop next time breakpoint',
427 print bpnum, 'is reached.'
428
429 def do_clear(self, arg):
430 """Three possibilities, tried in this order:
431 clear -> clear all breaks, ask for confirmation
432 clear file:lineno -> clear all breaks at file:lineno
433 clear bpno bpno ... -> clear breakpoints by number"""
434 if not arg:
435 try:
436 reply = raw_input('Clear all breaks? ')
437 except EOFError:
438 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000439 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000440 if reply in ('y', 'yes'):
441 self.clear_all_breaks()
442 return
443 if ':' in arg:
444 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000445 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000446 filename = arg[:i]
447 arg = arg[i+1:]
448 try:
449 lineno = int(arg)
450 except:
451 err = "Invalid line number (%s)" % arg
452 else:
453 err = self.clear_break(filename, lineno)
454 if err: print '***', err
455 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000456 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000457 for i in numberlist:
Georg Brandl6d2b3462005-08-24 07:36:17 +0000458 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
459 print 'No breakpoint numbered', i
460 continue
Tim Peters2344fae2001-01-15 00:50:52 +0000461 err = self.clear_bpbynumber(i)
462 if err:
463 print '***', err
464 else:
Georg Brandl6d2b3462005-08-24 07:36:17 +0000465 print 'Deleted breakpoint', i
Tim Peters2344fae2001-01-15 00:50:52 +0000466 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
467
468 def do_where(self, arg):
469 self.print_stack_trace()
470 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000471 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000472
473 def do_up(self, arg):
474 if self.curindex == 0:
475 print '*** Oldest frame'
476 else:
477 self.curindex = self.curindex - 1
478 self.curframe = self.stack[self.curindex][0]
479 self.print_stack_entry(self.stack[self.curindex])
480 self.lineno = None
481 do_u = do_up
482
483 def do_down(self, arg):
484 if self.curindex + 1 == len(self.stack):
485 print '*** Newest frame'
486 else:
487 self.curindex = self.curindex + 1
488 self.curframe = self.stack[self.curindex][0]
489 self.print_stack_entry(self.stack[self.curindex])
490 self.lineno = None
491 do_d = do_down
492
493 def do_step(self, arg):
494 self.set_step()
495 return 1
496 do_s = do_step
497
498 def do_next(self, arg):
499 self.set_next(self.curframe)
500 return 1
501 do_n = do_next
502
503 def do_return(self, arg):
504 self.set_return(self.curframe)
505 return 1
506 do_r = do_return
507
508 def do_continue(self, arg):
509 self.set_continue()
510 return 1
511 do_c = do_cont = do_continue
512
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000513 def do_jump(self, arg):
514 if self.curindex + 1 != len(self.stack):
515 print "*** You can only jump within the bottom frame"
516 return
517 try:
518 arg = int(arg)
519 except ValueError:
520 print "*** The 'jump' command requires a line number."
521 else:
522 try:
523 # Do the jump, fix up our copy of the stack, and display the
524 # new position
525 self.curframe.f_lineno = arg
526 self.stack[self.curindex] = self.stack[self.curindex][0], arg
527 self.print_stack_entry(self.stack[self.curindex])
528 except ValueError, e:
529 print '*** Jump failed:', e
530 do_j = do_jump
531
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000532 def do_debug(self, arg):
533 sys.settrace(None)
534 globals = self.curframe.f_globals
535 locals = self.curframe.f_locals
Guido van Rossumed538d82003-04-09 19:36:34 +0000536 p = Pdb()
537 p.prompt = "(%s) " % self.prompt.strip()
538 print "ENTERING RECURSIVE DEBUGGER"
539 sys.call_tracing(p.run, (arg, globals, locals))
540 print "LEAVING RECURSIVE DEBUGGER"
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000541 sys.settrace(self.trace_dispatch)
542 self.lastcmd = p.lastcmd
543
Tim Peters2344fae2001-01-15 00:50:52 +0000544 def do_quit(self, arg):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000545 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000546 self.set_quit()
547 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000548
Tim Peters2344fae2001-01-15 00:50:52 +0000549 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000550 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000551
Guido van Rossumeef26072003-01-13 21:13:55 +0000552 def do_EOF(self, arg):
553 print
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000554 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000555 self.set_quit()
556 return 1
557
Tim Peters2344fae2001-01-15 00:50:52 +0000558 def do_args(self, arg):
559 f = self.curframe
560 co = f.f_code
561 dict = f.f_locals
562 n = co.co_argcount
563 if co.co_flags & 4: n = n+1
564 if co.co_flags & 8: n = n+1
565 for i in range(n):
566 name = co.co_varnames[i]
567 print name, '=',
Raymond Hettinger54f02222002-06-01 14:18:47 +0000568 if name in dict: print dict[name]
Tim Peters2344fae2001-01-15 00:50:52 +0000569 else: print "*** undefined ***"
570 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000571
Tim Peters2344fae2001-01-15 00:50:52 +0000572 def do_retval(self, arg):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000573 if '__return__' in self.curframe.f_locals:
Tim Peters2344fae2001-01-15 00:50:52 +0000574 print self.curframe.f_locals['__return__']
575 else:
576 print '*** Not yet returned!'
577 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000578
Barry Warsaw210bd202002-11-05 22:40:20 +0000579 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000580 try:
Barry Warsaw210bd202002-11-05 22:40:20 +0000581 return eval(arg, self.curframe.f_globals,
582 self.curframe.f_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000583 except:
584 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000585 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000586 exc_type_name = t
587 else: exc_type_name = t.__name__
Walter Dörwald70a6b492004-02-12 17:35:32 +0000588 print '***', exc_type_name + ':', repr(v)
Barry Warsaw210bd202002-11-05 22:40:20 +0000589 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000590
Barry Warsaw210bd202002-11-05 22:40:20 +0000591 def do_p(self, arg):
592 try:
593 print repr(self._getval(arg))
594 except:
595 pass
596
597 def do_pp(self, arg):
598 try:
599 pprint.pprint(self._getval(arg))
600 except:
601 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000602
Tim Peters2344fae2001-01-15 00:50:52 +0000603 def do_list(self, arg):
604 self.lastcmd = 'list'
605 last = None
606 if arg:
607 try:
608 x = eval(arg, {}, {})
609 if type(x) == type(()):
610 first, last = x
611 first = int(first)
612 last = int(last)
613 if last < first:
614 # Assume it's a count
615 last = first + last
616 else:
617 first = max(1, int(x) - 5)
618 except:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000619 print '*** Error in argument:', repr(arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000620 return
621 elif self.lineno is None:
622 first = max(1, self.curframe.f_lineno - 5)
623 else:
624 first = self.lineno + 1
625 if last is None:
626 last = first + 10
627 filename = self.curframe.f_code.co_filename
628 breaklist = self.get_file_breaks(filename)
629 try:
630 for lineno in range(first, last+1):
631 line = linecache.getline(filename, lineno)
632 if not line:
633 print '[EOF]'
634 break
635 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000636 s = repr(lineno).rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000637 if len(s) < 4: s = s + ' '
638 if lineno in breaklist: s = s + 'B'
639 else: s = s + ' '
640 if lineno == self.curframe.f_lineno:
641 s = s + '->'
642 print s + '\t' + line,
643 self.lineno = lineno
644 except KeyboardInterrupt:
645 pass
646 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000647
Tim Peters2344fae2001-01-15 00:50:52 +0000648 def do_whatis(self, arg):
649 try:
650 value = eval(arg, self.curframe.f_globals,
651 self.curframe.f_locals)
652 except:
653 t, v = sys.exc_info()[:2]
654 if type(t) == type(''):
655 exc_type_name = t
656 else: exc_type_name = t.__name__
Walter Dörwald70a6b492004-02-12 17:35:32 +0000657 print '***', exc_type_name + ':', repr(v)
Tim Peters2344fae2001-01-15 00:50:52 +0000658 return
659 code = None
660 # Is it a function?
661 try: code = value.func_code
662 except: pass
663 if code:
664 print 'Function', code.co_name
665 return
666 # Is it an instance method?
667 try: code = value.im_func.func_code
668 except: pass
669 if code:
670 print 'Method', code.co_name
671 return
672 # None of the above...
673 print type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000674
Tim Peters2344fae2001-01-15 00:50:52 +0000675 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000676 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000677 if len(args) == 0:
678 keys = self.aliases.keys()
679 keys.sort()
680 for alias in keys:
681 print "%s = %s" % (alias, self.aliases[alias])
682 return
Guido van Rossum08454592002-07-12 13:10:53 +0000683 if args[0] in self.aliases and len(args) == 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000684 print "%s = %s" % (args[0], self.aliases[args[0]])
685 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000686 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000687
Tim Peters2344fae2001-01-15 00:50:52 +0000688 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000689 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000690 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000691 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000692 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000693
Tim Peters2344fae2001-01-15 00:50:52 +0000694 # Print a traceback starting at the top stack frame.
695 # The most recently entered frame is printed last;
696 # this is different from dbx and gdb, but consistent with
697 # the Python interpreter's stack trace.
698 # It is also consistent with the up/down commands (which are
699 # compatible with dbx and gdb: up moves towards 'main()'
700 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000701
Tim Peters2344fae2001-01-15 00:50:52 +0000702 def print_stack_trace(self):
703 try:
704 for frame_lineno in self.stack:
705 self.print_stack_entry(frame_lineno)
706 except KeyboardInterrupt:
707 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000708
Tim Peters2344fae2001-01-15 00:50:52 +0000709 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
710 frame, lineno = frame_lineno
711 if frame is self.curframe:
712 print '>',
713 else:
714 print ' ',
715 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000716
Guido van Rossum921c8241992-01-10 14:54:42 +0000717
Tim Peters2344fae2001-01-15 00:50:52 +0000718 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000719
Tim Peters2344fae2001-01-15 00:50:52 +0000720 def help_help(self):
721 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000722
Tim Peters2344fae2001-01-15 00:50:52 +0000723 def help_h(self):
724 print """h(elp)
725Without argument, print the list of available commands.
726With a command name as argument, print help about that command
727"help pdb" pipes the full documentation file to the $PAGER
728"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000729
Tim Peters2344fae2001-01-15 00:50:52 +0000730 def help_where(self):
731 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000732
Tim Peters2344fae2001-01-15 00:50:52 +0000733 def help_w(self):
734 print """w(here)
735Print a stack trace, with the most recent frame at the bottom.
736An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000737context of most commands. 'bt' is an alias for this command."""
738
739 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000740
Tim Peters2344fae2001-01-15 00:50:52 +0000741 def help_down(self):
742 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000743
Tim Peters2344fae2001-01-15 00:50:52 +0000744 def help_d(self):
745 print """d(own)
746Move the current frame one level down in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000747(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000748
Tim Peters2344fae2001-01-15 00:50:52 +0000749 def help_up(self):
750 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000751
Tim Peters2344fae2001-01-15 00:50:52 +0000752 def help_u(self):
753 print """u(p)
754Move the current frame one level up in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000755(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000756
Tim Peters2344fae2001-01-15 00:50:52 +0000757 def help_break(self):
758 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000759
Tim Peters2344fae2001-01-15 00:50:52 +0000760 def help_b(self):
761 print """b(reak) ([file:]lineno | function) [, condition]
762With a line number argument, set a break there in the current
763file. With a function name, set a break at first executable line
764of that function. Without argument, list all breaks. If a second
765argument is present, it is a string specifying an expression
766which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000767
Tim Peters2344fae2001-01-15 00:50:52 +0000768The line number may be prefixed with a filename and a colon,
769to specify a breakpoint in another file (probably one that
770hasn't been loaded yet). The file is searched for on sys.path;
771the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000772
Tim Peters2344fae2001-01-15 00:50:52 +0000773 def help_clear(self):
774 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000775
Tim Peters2344fae2001-01-15 00:50:52 +0000776 def help_cl(self):
777 print "cl(ear) filename:lineno"
778 print """cl(ear) [bpnumber [bpnumber...]]
779With a space separated list of breakpoint numbers, clear
780those breakpoints. Without argument, clear all breaks (but
781first ask confirmation). With a filename:lineno argument,
782clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000783
Tim Peters2344fae2001-01-15 00:50:52 +0000784Note that the argument is different from previous versions of
785the debugger (in python distributions 1.5.1 and before) where
786a linenumber was used instead of either filename:lineno or
787breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000788
Tim Peters2344fae2001-01-15 00:50:52 +0000789 def help_tbreak(self):
790 print """tbreak same arguments as break, but breakpoint is
791removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000792
Tim Peters2344fae2001-01-15 00:50:52 +0000793 def help_enable(self):
794 print """enable bpnumber [bpnumber ...]
795Enables the breakpoints given as a space separated list of
796bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000797
Tim Peters2344fae2001-01-15 00:50:52 +0000798 def help_disable(self):
799 print """disable bpnumber [bpnumber ...]
800Disables the breakpoints given as a space separated list of
801bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000802
Tim Peters2344fae2001-01-15 00:50:52 +0000803 def help_ignore(self):
804 print """ignore bpnumber count
805Sets the ignore count for the given breakpoint number. A breakpoint
806becomes active when the ignore count is zero. When non-zero, the
807count is decremented each time the breakpoint is reached and the
808breakpoint is not disabled and any associated condition evaluates
809to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000810
Tim Peters2344fae2001-01-15 00:50:52 +0000811 def help_condition(self):
812 print """condition bpnumber str_condition
813str_condition is a string specifying an expression which
814must evaluate to true before the breakpoint is honored.
815If str_condition is absent, any existing condition is removed;
816i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000817
Tim Peters2344fae2001-01-15 00:50:52 +0000818 def help_step(self):
819 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000820
Tim Peters2344fae2001-01-15 00:50:52 +0000821 def help_s(self):
822 print """s(tep)
823Execute the current line, stop at the first possible occasion
824(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000825
Tim Peters2344fae2001-01-15 00:50:52 +0000826 def help_next(self):
827 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000828
Tim Peters2344fae2001-01-15 00:50:52 +0000829 def help_n(self):
830 print """n(ext)
831Continue execution until the next line in the current function
832is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000833
Tim Peters2344fae2001-01-15 00:50:52 +0000834 def help_return(self):
835 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000836
Tim Peters2344fae2001-01-15 00:50:52 +0000837 def help_r(self):
838 print """r(eturn)
839Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000840
Tim Peters2344fae2001-01-15 00:50:52 +0000841 def help_continue(self):
842 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000843
Tim Peters2344fae2001-01-15 00:50:52 +0000844 def help_cont(self):
845 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000846
Tim Peters2344fae2001-01-15 00:50:52 +0000847 def help_c(self):
848 print """c(ont(inue))
849Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000850
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000851 def help_jump(self):
852 self.help_j()
853
854 def help_j(self):
855 print """j(ump) lineno
856Set the next line that will be executed."""
857
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000858 def help_debug(self):
859 print """debug code
860Enter a recursive debugger that steps through the code argument
861(which is an arbitrary expression or statement to be executed
862in the current environment)."""
863
Tim Peters2344fae2001-01-15 00:50:52 +0000864 def help_list(self):
865 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000866
Tim Peters2344fae2001-01-15 00:50:52 +0000867 def help_l(self):
868 print """l(ist) [first [,last]]
869List source code for the current file.
870Without arguments, list 11 lines around the current line
871or continue the previous listing.
872With one argument, list 11 lines starting at that line.
873With two arguments, list the given range;
874if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000875
Tim Peters2344fae2001-01-15 00:50:52 +0000876 def help_args(self):
877 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000878
Tim Peters2344fae2001-01-15 00:50:52 +0000879 def help_a(self):
880 print """a(rgs)
881Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000882
Tim Peters2344fae2001-01-15 00:50:52 +0000883 def help_p(self):
884 print """p expression
885Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000886
Barry Warsaw210bd202002-11-05 22:40:20 +0000887 def help_pp(self):
888 print """pp expression
889Pretty-print the value of the expression."""
890
Tim Peters2344fae2001-01-15 00:50:52 +0000891 def help_exec(self):
892 print """(!) statement
893Execute the (one-line) statement in the context of
894the current stack frame.
895The exclamation point can be omitted unless the first word
896of the statement resembles a debugger command.
897To assign to a global variable you must always prefix the
898command with a 'global' command, e.g.:
899(Pdb) global list_options; list_options = ['-l']
900(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000901
Tim Peters2344fae2001-01-15 00:50:52 +0000902 def help_quit(self):
903 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000904
Tim Peters2344fae2001-01-15 00:50:52 +0000905 def help_q(self):
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000906 print """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +0000907The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000908
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000909 help_exit = help_q
910
Tim Peters2344fae2001-01-15 00:50:52 +0000911 def help_whatis(self):
912 print """whatis arg
913Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000914
Tim Peters2344fae2001-01-15 00:50:52 +0000915 def help_EOF(self):
916 print """EOF
917Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000918
Tim Peters2344fae2001-01-15 00:50:52 +0000919 def help_alias(self):
920 print """alias [name [command [parameter parameter ...] ]]
921Creates an alias called 'name' the executes 'command'. The command
922must *not* be enclosed in quotes. Replaceable parameters are
923indicated by %1, %2, and so on, while %* is replaced by all the
924parameters. If no command is given, the current alias for name
925is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +0000926
Tim Peters2344fae2001-01-15 00:50:52 +0000927Aliases may be nested and can contain anything that can be
928legally typed at the pdb prompt. Note! You *can* override
929internal pdb commands with aliases! Those internal commands
930are then hidden until the alias is removed. Aliasing is recursively
931applied to the first word of the command line; all other words
932in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +0000933
Tim Peters2344fae2001-01-15 00:50:52 +0000934Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +0000935
Tim Peters2344fae2001-01-15 00:50:52 +0000936#Print instance variables (usage "pi classInst")
937alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +0000938
Tim Peters2344fae2001-01-15 00:50:52 +0000939#Print instance variables in self
940alias ps pi self
941"""
Guido van Rossum2424f851998-09-11 22:50:09 +0000942
Tim Peters2344fae2001-01-15 00:50:52 +0000943 def help_unalias(self):
944 print """unalias name
945Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000946
Tim Peters2344fae2001-01-15 00:50:52 +0000947 def help_pdb(self):
948 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000949
Tim Peters2344fae2001-01-15 00:50:52 +0000950 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000951 """Helper function for break/clear parsing -- may be overridden.
952
953 lookupmodule() translates (possibly incomplete) file or module name
954 into an absolute file name.
955 """
956 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +0000957 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000958 f = os.path.join(sys.path[0], filename)
959 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
960 return f
Tim Peters2344fae2001-01-15 00:50:52 +0000961 root, ext = os.path.splitext(filename)
962 if ext == '':
963 filename = filename + '.py'
964 if os.path.isabs(filename):
965 return filename
966 for dirname in sys.path:
967 while os.path.islink(dirname):
968 dirname = os.readlink(dirname)
969 fullname = os.path.join(dirname, filename)
970 if os.path.exists(fullname):
971 return fullname
972 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +0000973
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000974 def _runscript(self, filename):
975 # Start with fresh empty copy of globals and locals and tell the script
976 # that it's being run as __main__ to avoid scripts being able to access
977 # the pdb.py namespace.
Tim Peterse718f612004-10-12 21:51:32 +0000978 globals_ = {"__name__" : "__main__"}
979 locals_ = globals_
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000980
981 # When bdb sets tracing, a number of call and line events happens
982 # BEFORE debugger even reaches user's code (and the exact sequence of
983 # events depends on python version). So we take special measures to
984 # avoid stopping before we reach the main script (see user_line and
985 # user_call for details).
986 self._wait_for_mainpyfile = 1
987 self.mainpyfile = self.canonic(filename)
988 self._user_requested_quit = 0
989 statement = 'execfile( "%s")' % filename
990 self.run(statement, globals=globals_, locals=locals_)
991
Guido van Rossum35771131992-09-08 11:59:04 +0000992# Simplified interface
993
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000994def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000995 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000996
997def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000998 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000999
1000def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001001 # B/W compatibility
1002 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001003
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001004def runcall(*args, **kwds):
1005 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001006
Guido van Rossumb6775db1994-08-01 11:34:53 +00001007def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001008 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001009
1010# Post-Mortem interface
1011
1012def post_mortem(t):
Tim Peters2344fae2001-01-15 00:50:52 +00001013 p = Pdb()
1014 p.reset()
1015 while t.tb_next is not None:
1016 t = t.tb_next
1017 p.interaction(t.tb_frame, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001018
1019def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001020 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001021
1022
1023# Main program for testing
1024
Guido van Rossum23efba41992-01-27 16:58:47 +00001025TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001026
Guido van Rossum921c8241992-01-10 14:54:42 +00001027def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001028 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001029
1030# print help
1031def help():
Tim Peters2344fae2001-01-15 00:50:52 +00001032 for dirname in sys.path:
1033 fullname = os.path.join(dirname, 'pdb.doc')
1034 if os.path.exists(fullname):
1035 sts = os.system('${PAGER-more} '+fullname)
1036 if sts: print '*** Pager exit status:', sts
1037 break
1038 else:
1039 print 'Sorry, can\'t find the help file "pdb.doc"',
1040 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +00001041
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001042def main():
Tim Peters2344fae2001-01-15 00:50:52 +00001043 if not sys.argv[1:]:
1044 print "usage: pdb.py scriptfile [arg] ..."
1045 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001046
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001047 mainpyfile = sys.argv[1] # Get script filename
1048 if not os.path.exists(mainpyfile):
1049 print 'Error:', mainpyfile, 'does not exist'
Tim Peters2344fae2001-01-15 00:50:52 +00001050 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001051
Tim Peters2344fae2001-01-15 00:50:52 +00001052 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001053
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001054 # Replace pdb's dir with script's dir in front of module search path.
1055 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001056
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001057 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1058 # modified by the script being debugged. It's a bad idea when it was
1059 # changed by the user from the command line. The best approach would be to
1060 # have a "restart" command which would allow explicit specification of
1061 # command line arguments.
1062 pdb = Pdb()
1063 while 1:
1064 try:
1065 pdb._runscript(mainpyfile)
1066 if pdb._user_requested_quit:
1067 break
Tim Peterse718f612004-10-12 21:51:32 +00001068 print "The program finished and will be restarted"
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001069 except SystemExit:
1070 # In most cases SystemExit does not warrant a post-mortem session.
1071 print "The program exited via sys.exit(). Exit status: ",
1072 print sys.exc_info()[1]
1073 except:
1074 traceback.print_exc()
1075 print "Uncaught exception. Entering post mortem debugging"
1076 print "Running 'cont' or 'step' will restart the program"
1077 t = sys.exc_info()[2]
1078 while t.tb_next is not None:
1079 t = t.tb_next
1080 pdb.interaction(t.tb_frame,t)
1081 print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
1082
1083
1084# When invoked as main program, invoke the debugger on a script
1085if __name__=='__main__':
1086 main()