blob: 3c229ab772ad9f98e8302ebf22d1c30ffab18a8b [file] [log] [blame]
Guido van Rossumf06ee5f1996-11-27 19:52:01 +00001#! /usr/bin/env python
Guido van Rossumf17361d1996-07-30 16:28:13 +00002
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +00003"""A Python debugger."""
Guido van Rossum92df0c61992-01-14 18:30:15 +00004
Guido van Rossum23efba41992-01-27 16:58:47 +00005# (See pdb.doc for documentation.)
Guido van Rossum921c8241992-01-10 14:54:42 +00006
Guido van Rossum921c8241992-01-10 14:54:42 +00007import sys
8import linecache
Guido van Rossum23efba41992-01-27 16:58:47 +00009import cmd
10import bdb
Guido van Rossumef1b41b2002-09-10 21:57:14 +000011from repr import Repr
Guido van Rossumb5699c71998-07-20 23:13:54 +000012import os
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000013import re
Barry Warsaw210bd202002-11-05 22:40:20 +000014import pprint
Johannes Gijsbers25b38c82004-10-12 18:12:09 +000015import traceback
Guido van Rossumef1b41b2002-09-10 21:57:14 +000016# Create a custom safe Repr instance and increase its maxstring.
17# The default of 30 truncates error messages too easily.
18_repr = Repr()
19_repr.maxstring = 200
20_saferepr = _repr.repr
21
Skip Montanaro352674d2001-02-07 23:14:30 +000022__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
23 "post_mortem", "help"]
24
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000025def find_function(funcname, filename):
Tim Peters2344fae2001-01-15 00:50:52 +000026 cre = re.compile(r'def\s+%s\s*[(]' % funcname)
27 try:
28 fp = open(filename)
29 except IOError:
30 return None
31 # consumer of this info expects the first line to be 1
32 lineno = 1
33 answer = None
34 while 1:
35 line = fp.readline()
36 if line == '':
37 break
38 if cre.match(line):
39 answer = funcname, filename, lineno
40 break
41 lineno = lineno + 1
42 fp.close()
43 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +000044
45
Guido van Rossuma558e371994-11-10 22:27:35 +000046# Interaction prompt line will separate file and call info from code
47# text using value of line_prefix string. A newline and arrow may
48# be to your liking. You can set it once pdb is imported using the
49# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +000050# line_prefix = ': ' # Use this to get the old situation back
51line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +000052
Guido van Rossum23efba41992-01-27 16:58:47 +000053class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +000054
Tim Peters2344fae2001-01-15 00:50:52 +000055 def __init__(self):
56 bdb.Bdb.__init__(self)
57 cmd.Cmd.__init__(self)
58 self.prompt = '(Pdb) '
59 self.aliases = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +000060 self.mainpyfile = ''
61 self._wait_for_mainpyfile = 0
Tim Peters2344fae2001-01-15 00:50:52 +000062 # Try to load readline if it exists
63 try:
64 import readline
65 except ImportError:
66 pass
Guido van Rossum2424f851998-09-11 22:50:09 +000067
Tim Peters2344fae2001-01-15 00:50:52 +000068 # Read $HOME/.pdbrc and ./.pdbrc
69 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +000070 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +000071 envHome = os.environ['HOME']
72 try:
73 rcFile = open(os.path.join(envHome, ".pdbrc"))
74 except IOError:
75 pass
76 else:
77 for line in rcFile.readlines():
78 self.rcLines.append(line)
79 rcFile.close()
80 try:
81 rcFile = open(".pdbrc")
82 except IOError:
83 pass
84 else:
85 for line in rcFile.readlines():
86 self.rcLines.append(line)
87 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +000088
Tim Peters2344fae2001-01-15 00:50:52 +000089 def reset(self):
90 bdb.Bdb.reset(self)
91 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +000092
Tim Peters2344fae2001-01-15 00:50:52 +000093 def forget(self):
94 self.lineno = None
95 self.stack = []
96 self.curindex = 0
97 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +000098
Tim Peters2344fae2001-01-15 00:50:52 +000099 def setup(self, f, t):
100 self.forget()
101 self.stack, self.curindex = self.get_stack(f, t)
102 self.curframe = self.stack[self.curindex][0]
103 self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000104
Tim Peters2344fae2001-01-15 00:50:52 +0000105 # Can be executed earlier than 'setup' if desired
106 def execRcLines(self):
107 if self.rcLines:
108 # Make local copy because of recursion
109 rcLines = self.rcLines
110 # executed only once
111 self.rcLines = []
112 for line in rcLines:
113 line = line[:-1]
Guido van Rossum08454592002-07-12 13:10:53 +0000114 if len(line) > 0 and line[0] != '#':
115 self.onecmd(line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000116
Tim Peters280488b2002-08-23 18:19:30 +0000117 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000118
119 def user_call(self, frame, argument_list):
120 """This method is called when there is the remote possibility
121 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000122 if self._wait_for_mainpyfile:
123 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000124 if self.stop_here(frame):
125 print '--Call--'
126 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000127
Tim Peters2344fae2001-01-15 00:50:52 +0000128 def user_line(self, frame):
129 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000130 if self._wait_for_mainpyfile:
131 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
132 or frame.f_lineno<= 0):
133 return
134 self._wait_for_mainpyfile = 0
Tim Peters2344fae2001-01-15 00:50:52 +0000135 self.interaction(frame, None)
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000136
Tim Peters2344fae2001-01-15 00:50:52 +0000137 def user_return(self, frame, return_value):
138 """This function is called when a return trap is set here."""
139 frame.f_locals['__return__'] = return_value
140 print '--Return--'
141 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000142
Tim Peters2344fae2001-01-15 00:50:52 +0000143 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
144 """This function is called if an exception occurs,
145 but only if we are to stop at or just below this level."""
146 frame.f_locals['__exception__'] = exc_type, exc_value
147 if type(exc_type) == type(''):
148 exc_type_name = exc_type
149 else: exc_type_name = exc_type.__name__
Tim Peters6f8ee592001-02-09 23:28:07 +0000150 print exc_type_name + ':', _saferepr(exc_value)
Tim Peters2344fae2001-01-15 00:50:52 +0000151 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000152
Tim Peters2344fae2001-01-15 00:50:52 +0000153 # General interaction function
154
155 def interaction(self, frame, traceback):
156 self.setup(frame, traceback)
157 self.print_stack_entry(self.stack[self.curindex])
158 self.cmdloop()
159 self.forget()
160
161 def default(self, line):
162 if line[:1] == '!': line = line[1:]
163 locals = self.curframe.f_locals
164 globals = self.curframe.f_globals
165 try:
166 code = compile(line + '\n', '<stdin>', 'single')
167 exec code in globals, locals
168 except:
169 t, v = sys.exc_info()[:2]
170 if type(t) == type(''):
171 exc_type_name = t
172 else: exc_type_name = t.__name__
173 print '***', exc_type_name + ':', v
174
175 def precmd(self, line):
176 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000177 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000178 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000179 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000180 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000181 line = self.aliases[args[0]]
182 ii = 1
183 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000184 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000185 tmpArg)
186 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000187 line = line.replace("%*", ' '.join(args[1:]))
188 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000189 # split into ';;' separated commands
190 # unless it's an alias command
191 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000192 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000193 if marker >= 0:
194 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000195 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000196 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000197 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000198 return line
199
200 # Command definitions, called by cmdloop()
201 # The argument is the remaining string on the command line
202 # Return true to exit from the command loop
203
204 do_h = cmd.Cmd.do_help
205
Tim Peters2344fae2001-01-15 00:50:52 +0000206 def do_break(self, arg, temporary = 0):
207 # break [ ([filename:]lineno | function) [, "condition"] ]
208 if not arg:
209 if self.breaks: # There's at least one
210 print "Num Type Disp Enb Where"
211 for bp in bdb.Breakpoint.bpbynumber:
212 if bp:
213 bp.bpprint()
214 return
215 # parse arguments; comma has lowest precedence
216 # and cannot occur in filename
217 filename = None
218 lineno = None
219 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000220 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000221 if comma > 0:
222 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000223 cond = arg[comma+1:].lstrip()
224 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000225 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000226 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000227 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000228 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000229 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000230 f = self.lookupmodule(filename)
231 if not f:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000232 print '*** ', repr(filename),
Tim Peters2344fae2001-01-15 00:50:52 +0000233 print 'not found from sys.path'
234 return
235 else:
236 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000237 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000238 try:
239 lineno = int(arg)
240 except ValueError, msg:
241 print '*** Bad lineno:', arg
242 return
243 else:
244 # no colon; can be lineno or function
245 try:
246 lineno = int(arg)
247 except ValueError:
248 try:
249 func = eval(arg,
250 self.curframe.f_globals,
251 self.curframe.f_locals)
252 except:
253 func = arg
254 try:
255 if hasattr(func, 'im_func'):
256 func = func.im_func
257 code = func.func_code
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000258 #use co_name to identify the bkpt (function names
259 #could be aliased, but co_name is invariant)
260 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000261 lineno = code.co_firstlineno
262 filename = code.co_filename
263 except:
264 # last thing to try
265 (ok, filename, ln) = self.lineinfo(arg)
266 if not ok:
267 print '*** The specified object',
Walter Dörwald70a6b492004-02-12 17:35:32 +0000268 print repr(arg),
Tim Peters2344fae2001-01-15 00:50:52 +0000269 print 'is not a function'
270 print ('or was not found '
271 'along sys.path.')
272 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000273 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000274 lineno = int(ln)
275 if not filename:
276 filename = self.defaultFile()
277 # Check for reasonable breakpoint
278 line = self.checkline(filename, lineno)
279 if line:
280 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000281 err = self.set_break(filename, line, temporary, cond, funcname)
Tim Peters2344fae2001-01-15 00:50:52 +0000282 if err: print '***', err
283 else:
284 bp = self.get_breaks(filename, line)[-1]
285 print "Breakpoint %d at %s:%d" % (bp.number,
286 bp.file,
287 bp.line)
288
289 # To be overridden in derived debuggers
290 def defaultFile(self):
291 """Produce a reasonable default."""
292 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000293 if filename == '<string>' and self.mainpyfile:
294 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000295 return filename
296
297 do_b = do_break
298
299 def do_tbreak(self, arg):
300 self.do_break(arg, 1)
301
302 def lineinfo(self, identifier):
303 failed = (None, None, None)
304 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000305 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000306 if len(idstring) == 1:
307 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000308 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000309 elif len(idstring) == 3:
310 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000311 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000312 else:
313 return failed
314 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000315 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000316 # Protection for derived debuggers
317 if parts[0] == 'self':
318 del parts[0]
319 if len(parts) == 0:
320 return failed
321 # Best first guess at file to look at
322 fname = self.defaultFile()
323 if len(parts) == 1:
324 item = parts[0]
325 else:
326 # More than one part.
327 # First is module, second is method/class
328 f = self.lookupmodule(parts[0])
329 if f:
330 fname = f
331 item = parts[1]
332 answer = find_function(item, fname)
333 return answer or failed
334
335 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000336 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000337
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000338 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
339 line or EOF). Warning: testing is not comprehensive.
340 """
Tim Peters2344fae2001-01-15 00:50:52 +0000341 line = linecache.getline(filename, lineno)
342 if not line:
343 print 'End of file'
344 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000345 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000346 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000347 if (not line or (line[0] == '#') or
348 (line[:3] == '"""') or line[:3] == "'''"):
Tim Peters2344fae2001-01-15 00:50:52 +0000349 print '*** Blank or comment'
350 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000351 return lineno
352
353 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000354 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000355 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000356 try:
357 i = int(i)
358 except ValueError:
359 print 'Breakpoint index %r is not a number' % i
360 continue
361
362 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
363 print 'No breakpoint numbered', i
364 continue
365
366 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000367 if bp:
368 bp.enable()
369
370 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000371 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000372 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000373 try:
374 i = int(i)
375 except ValueError:
376 print 'Breakpoint index %r is not a number' % i
377 continue
Tim Petersf545baa2003-06-15 23:26:30 +0000378
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000379 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
380 print 'No breakpoint numbered', i
381 continue
382
383 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000384 if bp:
385 bp.disable()
386
387 def do_condition(self, arg):
388 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000389 args = arg.split(' ', 1)
390 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000391 try:
392 cond = args[1]
393 except:
394 cond = None
395 bp = bdb.Breakpoint.bpbynumber[bpnum]
396 if bp:
397 bp.cond = cond
398 if not cond:
399 print 'Breakpoint', bpnum,
400 print 'is now unconditional.'
401
402 def do_ignore(self,arg):
403 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000404 args = arg.split()
405 bpnum = int(args[0].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000406 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000407 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000408 except:
409 count = 0
410 bp = bdb.Breakpoint.bpbynumber[bpnum]
411 if bp:
412 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000413 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000414 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000415 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000416 reply = reply + '%d crossings' % count
417 else:
418 reply = reply + '1 crossing'
419 print reply + ' of breakpoint %d.' % bpnum
420 else:
421 print 'Will stop next time breakpoint',
422 print bpnum, 'is reached.'
423
424 def do_clear(self, arg):
425 """Three possibilities, tried in this order:
426 clear -> clear all breaks, ask for confirmation
427 clear file:lineno -> clear all breaks at file:lineno
428 clear bpno bpno ... -> clear breakpoints by number"""
429 if not arg:
430 try:
431 reply = raw_input('Clear all breaks? ')
432 except EOFError:
433 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000434 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000435 if reply in ('y', 'yes'):
436 self.clear_all_breaks()
437 return
438 if ':' in arg:
439 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000440 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000441 filename = arg[:i]
442 arg = arg[i+1:]
443 try:
444 lineno = int(arg)
445 except:
446 err = "Invalid line number (%s)" % arg
447 else:
448 err = self.clear_break(filename, lineno)
449 if err: print '***', err
450 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000451 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000452 for i in numberlist:
453 err = self.clear_bpbynumber(i)
454 if err:
455 print '***', err
456 else:
457 print 'Deleted breakpoint %s ' % (i,)
458 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
459
460 def do_where(self, arg):
461 self.print_stack_trace()
462 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000463 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000464
465 def do_up(self, arg):
466 if self.curindex == 0:
467 print '*** Oldest frame'
468 else:
469 self.curindex = self.curindex - 1
470 self.curframe = self.stack[self.curindex][0]
471 self.print_stack_entry(self.stack[self.curindex])
472 self.lineno = None
473 do_u = do_up
474
475 def do_down(self, arg):
476 if self.curindex + 1 == len(self.stack):
477 print '*** Newest frame'
478 else:
479 self.curindex = self.curindex + 1
480 self.curframe = self.stack[self.curindex][0]
481 self.print_stack_entry(self.stack[self.curindex])
482 self.lineno = None
483 do_d = do_down
484
485 def do_step(self, arg):
486 self.set_step()
487 return 1
488 do_s = do_step
489
490 def do_next(self, arg):
491 self.set_next(self.curframe)
492 return 1
493 do_n = do_next
494
495 def do_return(self, arg):
496 self.set_return(self.curframe)
497 return 1
498 do_r = do_return
499
500 def do_continue(self, arg):
501 self.set_continue()
502 return 1
503 do_c = do_cont = do_continue
504
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000505 def do_jump(self, arg):
506 if self.curindex + 1 != len(self.stack):
507 print "*** You can only jump within the bottom frame"
508 return
509 try:
510 arg = int(arg)
511 except ValueError:
512 print "*** The 'jump' command requires a line number."
513 else:
514 try:
515 # Do the jump, fix up our copy of the stack, and display the
516 # new position
517 self.curframe.f_lineno = arg
518 self.stack[self.curindex] = self.stack[self.curindex][0], arg
519 self.print_stack_entry(self.stack[self.curindex])
520 except ValueError, e:
521 print '*** Jump failed:', e
522 do_j = do_jump
523
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000524 def do_debug(self, arg):
525 sys.settrace(None)
526 globals = self.curframe.f_globals
527 locals = self.curframe.f_locals
Guido van Rossumed538d82003-04-09 19:36:34 +0000528 p = Pdb()
529 p.prompt = "(%s) " % self.prompt.strip()
530 print "ENTERING RECURSIVE DEBUGGER"
531 sys.call_tracing(p.run, (arg, globals, locals))
532 print "LEAVING RECURSIVE DEBUGGER"
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000533 sys.settrace(self.trace_dispatch)
534 self.lastcmd = p.lastcmd
535
Tim Peters2344fae2001-01-15 00:50:52 +0000536 def do_quit(self, arg):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000537 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000538 self.set_quit()
539 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000540
Tim Peters2344fae2001-01-15 00:50:52 +0000541 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000542 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000543
Guido van Rossumeef26072003-01-13 21:13:55 +0000544 def do_EOF(self, arg):
545 print
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000546 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000547 self.set_quit()
548 return 1
549
Tim Peters2344fae2001-01-15 00:50:52 +0000550 def do_args(self, arg):
551 f = self.curframe
552 co = f.f_code
553 dict = f.f_locals
554 n = co.co_argcount
555 if co.co_flags & 4: n = n+1
556 if co.co_flags & 8: n = n+1
557 for i in range(n):
558 name = co.co_varnames[i]
559 print name, '=',
Raymond Hettinger54f02222002-06-01 14:18:47 +0000560 if name in dict: print dict[name]
Tim Peters2344fae2001-01-15 00:50:52 +0000561 else: print "*** undefined ***"
562 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000563
Tim Peters2344fae2001-01-15 00:50:52 +0000564 def do_retval(self, arg):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000565 if '__return__' in self.curframe.f_locals:
Tim Peters2344fae2001-01-15 00:50:52 +0000566 print self.curframe.f_locals['__return__']
567 else:
568 print '*** Not yet returned!'
569 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000570
Barry Warsaw210bd202002-11-05 22:40:20 +0000571 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000572 try:
Barry Warsaw210bd202002-11-05 22:40:20 +0000573 return eval(arg, self.curframe.f_globals,
574 self.curframe.f_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000575 except:
576 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000577 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000578 exc_type_name = t
579 else: exc_type_name = t.__name__
Walter Dörwald70a6b492004-02-12 17:35:32 +0000580 print '***', exc_type_name + ':', repr(v)
Barry Warsaw210bd202002-11-05 22:40:20 +0000581 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000582
Barry Warsaw210bd202002-11-05 22:40:20 +0000583 def do_p(self, arg):
584 try:
585 print repr(self._getval(arg))
586 except:
587 pass
588
589 def do_pp(self, arg):
590 try:
591 pprint.pprint(self._getval(arg))
592 except:
593 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000594
Tim Peters2344fae2001-01-15 00:50:52 +0000595 def do_list(self, arg):
596 self.lastcmd = 'list'
597 last = None
598 if arg:
599 try:
600 x = eval(arg, {}, {})
601 if type(x) == type(()):
602 first, last = x
603 first = int(first)
604 last = int(last)
605 if last < first:
606 # Assume it's a count
607 last = first + last
608 else:
609 first = max(1, int(x) - 5)
610 except:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000611 print '*** Error in argument:', repr(arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000612 return
613 elif self.lineno is None:
614 first = max(1, self.curframe.f_lineno - 5)
615 else:
616 first = self.lineno + 1
617 if last is None:
618 last = first + 10
619 filename = self.curframe.f_code.co_filename
620 breaklist = self.get_file_breaks(filename)
621 try:
622 for lineno in range(first, last+1):
623 line = linecache.getline(filename, lineno)
624 if not line:
625 print '[EOF]'
626 break
627 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000628 s = repr(lineno).rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000629 if len(s) < 4: s = s + ' '
630 if lineno in breaklist: s = s + 'B'
631 else: s = s + ' '
632 if lineno == self.curframe.f_lineno:
633 s = s + '->'
634 print s + '\t' + line,
635 self.lineno = lineno
636 except KeyboardInterrupt:
637 pass
638 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000639
Tim Peters2344fae2001-01-15 00:50:52 +0000640 def do_whatis(self, arg):
641 try:
642 value = eval(arg, self.curframe.f_globals,
643 self.curframe.f_locals)
644 except:
645 t, v = sys.exc_info()[:2]
646 if type(t) == type(''):
647 exc_type_name = t
648 else: exc_type_name = t.__name__
Walter Dörwald70a6b492004-02-12 17:35:32 +0000649 print '***', exc_type_name + ':', repr(v)
Tim Peters2344fae2001-01-15 00:50:52 +0000650 return
651 code = None
652 # Is it a function?
653 try: code = value.func_code
654 except: pass
655 if code:
656 print 'Function', code.co_name
657 return
658 # Is it an instance method?
659 try: code = value.im_func.func_code
660 except: pass
661 if code:
662 print 'Method', code.co_name
663 return
664 # None of the above...
665 print type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000666
Tim Peters2344fae2001-01-15 00:50:52 +0000667 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000668 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000669 if len(args) == 0:
670 keys = self.aliases.keys()
671 keys.sort()
672 for alias in keys:
673 print "%s = %s" % (alias, self.aliases[alias])
674 return
Guido van Rossum08454592002-07-12 13:10:53 +0000675 if args[0] in self.aliases and len(args) == 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000676 print "%s = %s" % (args[0], self.aliases[args[0]])
677 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000678 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000679
Tim Peters2344fae2001-01-15 00:50:52 +0000680 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000681 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000682 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000683 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000684 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000685
Tim Peters2344fae2001-01-15 00:50:52 +0000686 # Print a traceback starting at the top stack frame.
687 # The most recently entered frame is printed last;
688 # this is different from dbx and gdb, but consistent with
689 # the Python interpreter's stack trace.
690 # It is also consistent with the up/down commands (which are
691 # compatible with dbx and gdb: up moves towards 'main()'
692 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000693
Tim Peters2344fae2001-01-15 00:50:52 +0000694 def print_stack_trace(self):
695 try:
696 for frame_lineno in self.stack:
697 self.print_stack_entry(frame_lineno)
698 except KeyboardInterrupt:
699 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000700
Tim Peters2344fae2001-01-15 00:50:52 +0000701 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
702 frame, lineno = frame_lineno
703 if frame is self.curframe:
704 print '>',
705 else:
706 print ' ',
707 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000708
Guido van Rossum921c8241992-01-10 14:54:42 +0000709
Tim Peters2344fae2001-01-15 00:50:52 +0000710 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000711
Tim Peters2344fae2001-01-15 00:50:52 +0000712 def help_help(self):
713 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000714
Tim Peters2344fae2001-01-15 00:50:52 +0000715 def help_h(self):
716 print """h(elp)
717Without argument, print the list of available commands.
718With a command name as argument, print help about that command
719"help pdb" pipes the full documentation file to the $PAGER
720"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000721
Tim Peters2344fae2001-01-15 00:50:52 +0000722 def help_where(self):
723 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000724
Tim Peters2344fae2001-01-15 00:50:52 +0000725 def help_w(self):
726 print """w(here)
727Print a stack trace, with the most recent frame at the bottom.
728An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000729context of most commands. 'bt' is an alias for this command."""
730
731 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000732
Tim Peters2344fae2001-01-15 00:50:52 +0000733 def help_down(self):
734 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000735
Tim Peters2344fae2001-01-15 00:50:52 +0000736 def help_d(self):
737 print """d(own)
738Move the current frame one level down in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000739(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000740
Tim Peters2344fae2001-01-15 00:50:52 +0000741 def help_up(self):
742 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000743
Tim Peters2344fae2001-01-15 00:50:52 +0000744 def help_u(self):
745 print """u(p)
746Move the current frame one level up in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000747(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000748
Tim Peters2344fae2001-01-15 00:50:52 +0000749 def help_break(self):
750 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000751
Tim Peters2344fae2001-01-15 00:50:52 +0000752 def help_b(self):
753 print """b(reak) ([file:]lineno | function) [, condition]
754With a line number argument, set a break there in the current
755file. With a function name, set a break at first executable line
756of that function. Without argument, list all breaks. If a second
757argument is present, it is a string specifying an expression
758which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000759
Tim Peters2344fae2001-01-15 00:50:52 +0000760The line number may be prefixed with a filename and a colon,
761to specify a breakpoint in another file (probably one that
762hasn't been loaded yet). The file is searched for on sys.path;
763the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000764
Tim Peters2344fae2001-01-15 00:50:52 +0000765 def help_clear(self):
766 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000767
Tim Peters2344fae2001-01-15 00:50:52 +0000768 def help_cl(self):
769 print "cl(ear) filename:lineno"
770 print """cl(ear) [bpnumber [bpnumber...]]
771With a space separated list of breakpoint numbers, clear
772those breakpoints. Without argument, clear all breaks (but
773first ask confirmation). With a filename:lineno argument,
774clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000775
Tim Peters2344fae2001-01-15 00:50:52 +0000776Note that the argument is different from previous versions of
777the debugger (in python distributions 1.5.1 and before) where
778a linenumber was used instead of either filename:lineno or
779breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000780
Tim Peters2344fae2001-01-15 00:50:52 +0000781 def help_tbreak(self):
782 print """tbreak same arguments as break, but breakpoint is
783removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000784
Tim Peters2344fae2001-01-15 00:50:52 +0000785 def help_enable(self):
786 print """enable bpnumber [bpnumber ...]
787Enables the breakpoints given as a space separated list of
788bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000789
Tim Peters2344fae2001-01-15 00:50:52 +0000790 def help_disable(self):
791 print """disable bpnumber [bpnumber ...]
792Disables the breakpoints given as a space separated list of
793bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000794
Tim Peters2344fae2001-01-15 00:50:52 +0000795 def help_ignore(self):
796 print """ignore bpnumber count
797Sets the ignore count for the given breakpoint number. A breakpoint
798becomes active when the ignore count is zero. When non-zero, the
799count is decremented each time the breakpoint is reached and the
800breakpoint is not disabled and any associated condition evaluates
801to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000802
Tim Peters2344fae2001-01-15 00:50:52 +0000803 def help_condition(self):
804 print """condition bpnumber str_condition
805str_condition is a string specifying an expression which
806must evaluate to true before the breakpoint is honored.
807If str_condition is absent, any existing condition is removed;
808i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000809
Tim Peters2344fae2001-01-15 00:50:52 +0000810 def help_step(self):
811 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000812
Tim Peters2344fae2001-01-15 00:50:52 +0000813 def help_s(self):
814 print """s(tep)
815Execute the current line, stop at the first possible occasion
816(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000817
Tim Peters2344fae2001-01-15 00:50:52 +0000818 def help_next(self):
819 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000820
Tim Peters2344fae2001-01-15 00:50:52 +0000821 def help_n(self):
822 print """n(ext)
823Continue execution until the next line in the current function
824is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000825
Tim Peters2344fae2001-01-15 00:50:52 +0000826 def help_return(self):
827 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000828
Tim Peters2344fae2001-01-15 00:50:52 +0000829 def help_r(self):
830 print """r(eturn)
831Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000832
Tim Peters2344fae2001-01-15 00:50:52 +0000833 def help_continue(self):
834 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000835
Tim Peters2344fae2001-01-15 00:50:52 +0000836 def help_cont(self):
837 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000838
Tim Peters2344fae2001-01-15 00:50:52 +0000839 def help_c(self):
840 print """c(ont(inue))
841Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000842
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000843 def help_jump(self):
844 self.help_j()
845
846 def help_j(self):
847 print """j(ump) lineno
848Set the next line that will be executed."""
849
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000850 def help_debug(self):
851 print """debug code
852Enter a recursive debugger that steps through the code argument
853(which is an arbitrary expression or statement to be executed
854in the current environment)."""
855
Tim Peters2344fae2001-01-15 00:50:52 +0000856 def help_list(self):
857 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000858
Tim Peters2344fae2001-01-15 00:50:52 +0000859 def help_l(self):
860 print """l(ist) [first [,last]]
861List source code for the current file.
862Without arguments, list 11 lines around the current line
863or continue the previous listing.
864With one argument, list 11 lines starting at that line.
865With two arguments, list the given range;
866if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000867
Tim Peters2344fae2001-01-15 00:50:52 +0000868 def help_args(self):
869 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000870
Tim Peters2344fae2001-01-15 00:50:52 +0000871 def help_a(self):
872 print """a(rgs)
873Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000874
Tim Peters2344fae2001-01-15 00:50:52 +0000875 def help_p(self):
876 print """p expression
877Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000878
Barry Warsaw210bd202002-11-05 22:40:20 +0000879 def help_pp(self):
880 print """pp expression
881Pretty-print the value of the expression."""
882
Tim Peters2344fae2001-01-15 00:50:52 +0000883 def help_exec(self):
884 print """(!) statement
885Execute the (one-line) statement in the context of
886the current stack frame.
887The exclamation point can be omitted unless the first word
888of the statement resembles a debugger command.
889To assign to a global variable you must always prefix the
890command with a 'global' command, e.g.:
891(Pdb) global list_options; list_options = ['-l']
892(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000893
Tim Peters2344fae2001-01-15 00:50:52 +0000894 def help_quit(self):
895 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000896
Tim Peters2344fae2001-01-15 00:50:52 +0000897 def help_q(self):
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000898 print """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +0000899The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000900
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000901 help_exit = help_q
902
Tim Peters2344fae2001-01-15 00:50:52 +0000903 def help_whatis(self):
904 print """whatis arg
905Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000906
Tim Peters2344fae2001-01-15 00:50:52 +0000907 def help_EOF(self):
908 print """EOF
909Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000910
Tim Peters2344fae2001-01-15 00:50:52 +0000911 def help_alias(self):
912 print """alias [name [command [parameter parameter ...] ]]
913Creates an alias called 'name' the executes 'command'. The command
914must *not* be enclosed in quotes. Replaceable parameters are
915indicated by %1, %2, and so on, while %* is replaced by all the
916parameters. If no command is given, the current alias for name
917is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +0000918
Tim Peters2344fae2001-01-15 00:50:52 +0000919Aliases may be nested and can contain anything that can be
920legally typed at the pdb prompt. Note! You *can* override
921internal pdb commands with aliases! Those internal commands
922are then hidden until the alias is removed. Aliasing is recursively
923applied to the first word of the command line; all other words
924in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +0000925
Tim Peters2344fae2001-01-15 00:50:52 +0000926Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +0000927
Tim Peters2344fae2001-01-15 00:50:52 +0000928#Print instance variables (usage "pi classInst")
929alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +0000930
Tim Peters2344fae2001-01-15 00:50:52 +0000931#Print instance variables in self
932alias ps pi self
933"""
Guido van Rossum2424f851998-09-11 22:50:09 +0000934
Tim Peters2344fae2001-01-15 00:50:52 +0000935 def help_unalias(self):
936 print """unalias name
937Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000938
Tim Peters2344fae2001-01-15 00:50:52 +0000939 def help_pdb(self):
940 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000941
Tim Peters2344fae2001-01-15 00:50:52 +0000942 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000943 """Helper function for break/clear parsing -- may be overridden.
944
945 lookupmodule() translates (possibly incomplete) file or module name
946 into an absolute file name.
947 """
948 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +0000949 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000950 f = os.path.join(sys.path[0], filename)
951 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
952 return f
Tim Peters2344fae2001-01-15 00:50:52 +0000953 root, ext = os.path.splitext(filename)
954 if ext == '':
955 filename = filename + '.py'
956 if os.path.isabs(filename):
957 return filename
958 for dirname in sys.path:
959 while os.path.islink(dirname):
960 dirname = os.readlink(dirname)
961 fullname = os.path.join(dirname, filename)
962 if os.path.exists(fullname):
963 return fullname
964 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +0000965
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000966 def _runscript(self, filename):
967 # Start with fresh empty copy of globals and locals and tell the script
968 # that it's being run as __main__ to avoid scripts being able to access
969 # the pdb.py namespace.
Tim Peterse718f612004-10-12 21:51:32 +0000970 globals_ = {"__name__" : "__main__"}
971 locals_ = globals_
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000972
973 # When bdb sets tracing, a number of call and line events happens
974 # BEFORE debugger even reaches user's code (and the exact sequence of
975 # events depends on python version). So we take special measures to
976 # avoid stopping before we reach the main script (see user_line and
977 # user_call for details).
978 self._wait_for_mainpyfile = 1
979 self.mainpyfile = self.canonic(filename)
980 self._user_requested_quit = 0
981 statement = 'execfile( "%s")' % filename
982 self.run(statement, globals=globals_, locals=locals_)
983
Guido van Rossum35771131992-09-08 11:59:04 +0000984# Simplified interface
985
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000986def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000987 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000988
989def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000990 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000991
992def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +0000993 # B/W compatibility
994 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000995
Guido van Rossum4e160981992-09-02 20:43:20 +0000996def runcall(*args):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000997 return Pdb().runcall(*args)
Guido van Rossum4e160981992-09-02 20:43:20 +0000998
Guido van Rossumb6775db1994-08-01 11:34:53 +0000999def set_trace():
Tim Peters2344fae2001-01-15 00:50:52 +00001000 Pdb().set_trace()
Guido van Rossum35771131992-09-08 11:59:04 +00001001
1002# Post-Mortem interface
1003
1004def post_mortem(t):
Tim Peters2344fae2001-01-15 00:50:52 +00001005 p = Pdb()
1006 p.reset()
1007 while t.tb_next is not None:
1008 t = t.tb_next
1009 p.interaction(t.tb_frame, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001010
1011def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001012 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001013
1014
1015# Main program for testing
1016
Guido van Rossum23efba41992-01-27 16:58:47 +00001017TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001018
Guido van Rossum921c8241992-01-10 14:54:42 +00001019def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001020 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001021
1022# print help
1023def help():
Tim Peters2344fae2001-01-15 00:50:52 +00001024 for dirname in sys.path:
1025 fullname = os.path.join(dirname, 'pdb.doc')
1026 if os.path.exists(fullname):
1027 sts = os.system('${PAGER-more} '+fullname)
1028 if sts: print '*** Pager exit status:', sts
1029 break
1030 else:
1031 print 'Sorry, can\'t find the help file "pdb.doc"',
1032 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +00001033
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001034def main():
Tim Peters2344fae2001-01-15 00:50:52 +00001035 if not sys.argv[1:]:
1036 print "usage: pdb.py scriptfile [arg] ..."
1037 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001038
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001039 mainpyfile = sys.argv[1] # Get script filename
1040 if not os.path.exists(mainpyfile):
1041 print 'Error:', mainpyfile, 'does not exist'
Tim Peters2344fae2001-01-15 00:50:52 +00001042 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001043
Tim Peters2344fae2001-01-15 00:50:52 +00001044 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001045
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001046 # Replace pdb's dir with script's dir in front of module search path.
1047 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001048
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001049 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1050 # modified by the script being debugged. It's a bad idea when it was
1051 # changed by the user from the command line. The best approach would be to
1052 # have a "restart" command which would allow explicit specification of
1053 # command line arguments.
1054 pdb = Pdb()
1055 while 1:
1056 try:
1057 pdb._runscript(mainpyfile)
1058 if pdb._user_requested_quit:
1059 break
Tim Peterse718f612004-10-12 21:51:32 +00001060 print "The program finished and will be restarted"
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001061 except SystemExit:
1062 # In most cases SystemExit does not warrant a post-mortem session.
1063 print "The program exited via sys.exit(). Exit status: ",
1064 print sys.exc_info()[1]
1065 except:
1066 traceback.print_exc()
1067 print "Uncaught exception. Entering post mortem debugging"
1068 print "Running 'cont' or 'step' will restart the program"
1069 t = sys.exc_info()[2]
1070 while t.tb_next is not None:
1071 t = t.tb_next
1072 pdb.interaction(t.tb_frame,t)
1073 print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
1074
1075
1076# When invoked as main program, invoke the debugger on a script
1077if __name__=='__main__':
1078 main()