blob: b00f68b79d50f7f20305b13565fabc31e1191ed9 [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:
Georg Brandl6d2b3462005-08-24 07:36:17 +0000453 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
454 print 'No breakpoint numbered', i
455 continue
Tim Peters2344fae2001-01-15 00:50:52 +0000456 err = self.clear_bpbynumber(i)
457 if err:
458 print '***', err
459 else:
Georg Brandl6d2b3462005-08-24 07:36:17 +0000460 print 'Deleted breakpoint', i
Tim Peters2344fae2001-01-15 00:50:52 +0000461 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
462
463 def do_where(self, arg):
464 self.print_stack_trace()
465 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000466 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000467
468 def do_up(self, arg):
469 if self.curindex == 0:
470 print '*** Oldest frame'
471 else:
472 self.curindex = self.curindex - 1
473 self.curframe = self.stack[self.curindex][0]
474 self.print_stack_entry(self.stack[self.curindex])
475 self.lineno = None
476 do_u = do_up
477
478 def do_down(self, arg):
479 if self.curindex + 1 == len(self.stack):
480 print '*** Newest frame'
481 else:
482 self.curindex = self.curindex + 1
483 self.curframe = self.stack[self.curindex][0]
484 self.print_stack_entry(self.stack[self.curindex])
485 self.lineno = None
486 do_d = do_down
487
488 def do_step(self, arg):
489 self.set_step()
490 return 1
491 do_s = do_step
492
493 def do_next(self, arg):
494 self.set_next(self.curframe)
495 return 1
496 do_n = do_next
497
498 def do_return(self, arg):
499 self.set_return(self.curframe)
500 return 1
501 do_r = do_return
502
503 def do_continue(self, arg):
504 self.set_continue()
505 return 1
506 do_c = do_cont = do_continue
507
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000508 def do_jump(self, arg):
509 if self.curindex + 1 != len(self.stack):
510 print "*** You can only jump within the bottom frame"
511 return
512 try:
513 arg = int(arg)
514 except ValueError:
515 print "*** The 'jump' command requires a line number."
516 else:
517 try:
518 # Do the jump, fix up our copy of the stack, and display the
519 # new position
520 self.curframe.f_lineno = arg
521 self.stack[self.curindex] = self.stack[self.curindex][0], arg
522 self.print_stack_entry(self.stack[self.curindex])
523 except ValueError, e:
524 print '*** Jump failed:', e
525 do_j = do_jump
526
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000527 def do_debug(self, arg):
528 sys.settrace(None)
529 globals = self.curframe.f_globals
530 locals = self.curframe.f_locals
Guido van Rossumed538d82003-04-09 19:36:34 +0000531 p = Pdb()
532 p.prompt = "(%s) " % self.prompt.strip()
533 print "ENTERING RECURSIVE DEBUGGER"
534 sys.call_tracing(p.run, (arg, globals, locals))
535 print "LEAVING RECURSIVE DEBUGGER"
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000536 sys.settrace(self.trace_dispatch)
537 self.lastcmd = p.lastcmd
538
Tim Peters2344fae2001-01-15 00:50:52 +0000539 def do_quit(self, arg):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000540 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000541 self.set_quit()
542 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000543
Tim Peters2344fae2001-01-15 00:50:52 +0000544 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000545 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000546
Guido van Rossumeef26072003-01-13 21:13:55 +0000547 def do_EOF(self, arg):
548 print
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000549 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000550 self.set_quit()
551 return 1
552
Tim Peters2344fae2001-01-15 00:50:52 +0000553 def do_args(self, arg):
554 f = self.curframe
555 co = f.f_code
556 dict = f.f_locals
557 n = co.co_argcount
558 if co.co_flags & 4: n = n+1
559 if co.co_flags & 8: n = n+1
560 for i in range(n):
561 name = co.co_varnames[i]
562 print name, '=',
Raymond Hettinger54f02222002-06-01 14:18:47 +0000563 if name in dict: print dict[name]
Tim Peters2344fae2001-01-15 00:50:52 +0000564 else: print "*** undefined ***"
565 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000566
Tim Peters2344fae2001-01-15 00:50:52 +0000567 def do_retval(self, arg):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000568 if '__return__' in self.curframe.f_locals:
Tim Peters2344fae2001-01-15 00:50:52 +0000569 print self.curframe.f_locals['__return__']
570 else:
571 print '*** Not yet returned!'
572 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000573
Barry Warsaw210bd202002-11-05 22:40:20 +0000574 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000575 try:
Barry Warsaw210bd202002-11-05 22:40:20 +0000576 return eval(arg, self.curframe.f_globals,
577 self.curframe.f_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000578 except:
579 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000580 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000581 exc_type_name = t
582 else: exc_type_name = t.__name__
Walter Dörwald70a6b492004-02-12 17:35:32 +0000583 print '***', exc_type_name + ':', repr(v)
Barry Warsaw210bd202002-11-05 22:40:20 +0000584 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000585
Barry Warsaw210bd202002-11-05 22:40:20 +0000586 def do_p(self, arg):
587 try:
588 print repr(self._getval(arg))
589 except:
590 pass
591
592 def do_pp(self, arg):
593 try:
594 pprint.pprint(self._getval(arg))
595 except:
596 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000597
Tim Peters2344fae2001-01-15 00:50:52 +0000598 def do_list(self, arg):
599 self.lastcmd = 'list'
600 last = None
601 if arg:
602 try:
603 x = eval(arg, {}, {})
604 if type(x) == type(()):
605 first, last = x
606 first = int(first)
607 last = int(last)
608 if last < first:
609 # Assume it's a count
610 last = first + last
611 else:
612 first = max(1, int(x) - 5)
613 except:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000614 print '*** Error in argument:', repr(arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000615 return
616 elif self.lineno is None:
617 first = max(1, self.curframe.f_lineno - 5)
618 else:
619 first = self.lineno + 1
620 if last is None:
621 last = first + 10
622 filename = self.curframe.f_code.co_filename
623 breaklist = self.get_file_breaks(filename)
624 try:
625 for lineno in range(first, last+1):
626 line = linecache.getline(filename, lineno)
627 if not line:
628 print '[EOF]'
629 break
630 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000631 s = repr(lineno).rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000632 if len(s) < 4: s = s + ' '
633 if lineno in breaklist: s = s + 'B'
634 else: s = s + ' '
635 if lineno == self.curframe.f_lineno:
636 s = s + '->'
637 print s + '\t' + line,
638 self.lineno = lineno
639 except KeyboardInterrupt:
640 pass
641 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000642
Tim Peters2344fae2001-01-15 00:50:52 +0000643 def do_whatis(self, arg):
644 try:
645 value = eval(arg, self.curframe.f_globals,
646 self.curframe.f_locals)
647 except:
648 t, v = sys.exc_info()[:2]
649 if type(t) == type(''):
650 exc_type_name = t
651 else: exc_type_name = t.__name__
Walter Dörwald70a6b492004-02-12 17:35:32 +0000652 print '***', exc_type_name + ':', repr(v)
Tim Peters2344fae2001-01-15 00:50:52 +0000653 return
654 code = None
655 # Is it a function?
656 try: code = value.func_code
657 except: pass
658 if code:
659 print 'Function', code.co_name
660 return
661 # Is it an instance method?
662 try: code = value.im_func.func_code
663 except: pass
664 if code:
665 print 'Method', code.co_name
666 return
667 # None of the above...
668 print type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000669
Tim Peters2344fae2001-01-15 00:50:52 +0000670 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000671 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000672 if len(args) == 0:
673 keys = self.aliases.keys()
674 keys.sort()
675 for alias in keys:
676 print "%s = %s" % (alias, self.aliases[alias])
677 return
Guido van Rossum08454592002-07-12 13:10:53 +0000678 if args[0] in self.aliases and len(args) == 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000679 print "%s = %s" % (args[0], self.aliases[args[0]])
680 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000681 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000682
Tim Peters2344fae2001-01-15 00:50:52 +0000683 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000684 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000685 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000686 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000687 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000688
Tim Peters2344fae2001-01-15 00:50:52 +0000689 # Print a traceback starting at the top stack frame.
690 # The most recently entered frame is printed last;
691 # this is different from dbx and gdb, but consistent with
692 # the Python interpreter's stack trace.
693 # It is also consistent with the up/down commands (which are
694 # compatible with dbx and gdb: up moves towards 'main()'
695 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000696
Tim Peters2344fae2001-01-15 00:50:52 +0000697 def print_stack_trace(self):
698 try:
699 for frame_lineno in self.stack:
700 self.print_stack_entry(frame_lineno)
701 except KeyboardInterrupt:
702 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000703
Tim Peters2344fae2001-01-15 00:50:52 +0000704 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
705 frame, lineno = frame_lineno
706 if frame is self.curframe:
707 print '>',
708 else:
709 print ' ',
710 print self.format_stack_entry(frame_lineno, prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000711
Guido van Rossum921c8241992-01-10 14:54:42 +0000712
Tim Peters2344fae2001-01-15 00:50:52 +0000713 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000714
Tim Peters2344fae2001-01-15 00:50:52 +0000715 def help_help(self):
716 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000717
Tim Peters2344fae2001-01-15 00:50:52 +0000718 def help_h(self):
719 print """h(elp)
720Without argument, print the list of available commands.
721With a command name as argument, print help about that command
722"help pdb" pipes the full documentation file to the $PAGER
723"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000724
Tim Peters2344fae2001-01-15 00:50:52 +0000725 def help_where(self):
726 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000727
Tim Peters2344fae2001-01-15 00:50:52 +0000728 def help_w(self):
729 print """w(here)
730Print a stack trace, with the most recent frame at the bottom.
731An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000732context of most commands. 'bt' is an alias for this command."""
733
734 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000735
Tim Peters2344fae2001-01-15 00:50:52 +0000736 def help_down(self):
737 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000738
Tim Peters2344fae2001-01-15 00:50:52 +0000739 def help_d(self):
740 print """d(own)
741Move the current frame one level down in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000742(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000743
Tim Peters2344fae2001-01-15 00:50:52 +0000744 def help_up(self):
745 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000746
Tim Peters2344fae2001-01-15 00:50:52 +0000747 def help_u(self):
748 print """u(p)
749Move the current frame one level up in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000750(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000751
Tim Peters2344fae2001-01-15 00:50:52 +0000752 def help_break(self):
753 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000754
Tim Peters2344fae2001-01-15 00:50:52 +0000755 def help_b(self):
756 print """b(reak) ([file:]lineno | function) [, condition]
757With a line number argument, set a break there in the current
758file. With a function name, set a break at first executable line
759of that function. Without argument, list all breaks. If a second
760argument is present, it is a string specifying an expression
761which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000762
Tim Peters2344fae2001-01-15 00:50:52 +0000763The line number may be prefixed with a filename and a colon,
764to specify a breakpoint in another file (probably one that
765hasn't been loaded yet). The file is searched for on sys.path;
766the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000767
Tim Peters2344fae2001-01-15 00:50:52 +0000768 def help_clear(self):
769 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000770
Tim Peters2344fae2001-01-15 00:50:52 +0000771 def help_cl(self):
772 print "cl(ear) filename:lineno"
773 print """cl(ear) [bpnumber [bpnumber...]]
774With a space separated list of breakpoint numbers, clear
775those breakpoints. Without argument, clear all breaks (but
776first ask confirmation). With a filename:lineno argument,
777clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000778
Tim Peters2344fae2001-01-15 00:50:52 +0000779Note that the argument is different from previous versions of
780the debugger (in python distributions 1.5.1 and before) where
781a linenumber was used instead of either filename:lineno or
782breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000783
Tim Peters2344fae2001-01-15 00:50:52 +0000784 def help_tbreak(self):
785 print """tbreak same arguments as break, but breakpoint is
786removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000787
Tim Peters2344fae2001-01-15 00:50:52 +0000788 def help_enable(self):
789 print """enable bpnumber [bpnumber ...]
790Enables the breakpoints given as a space separated list of
791bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000792
Tim Peters2344fae2001-01-15 00:50:52 +0000793 def help_disable(self):
794 print """disable bpnumber [bpnumber ...]
795Disables 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_ignore(self):
799 print """ignore bpnumber count
800Sets the ignore count for the given breakpoint number. A breakpoint
801becomes active when the ignore count is zero. When non-zero, the
802count is decremented each time the breakpoint is reached and the
803breakpoint is not disabled and any associated condition evaluates
804to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000805
Tim Peters2344fae2001-01-15 00:50:52 +0000806 def help_condition(self):
807 print """condition bpnumber str_condition
808str_condition is a string specifying an expression which
809must evaluate to true before the breakpoint is honored.
810If str_condition is absent, any existing condition is removed;
811i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000812
Tim Peters2344fae2001-01-15 00:50:52 +0000813 def help_step(self):
814 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000815
Tim Peters2344fae2001-01-15 00:50:52 +0000816 def help_s(self):
817 print """s(tep)
818Execute the current line, stop at the first possible occasion
819(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000820
Tim Peters2344fae2001-01-15 00:50:52 +0000821 def help_next(self):
822 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000823
Tim Peters2344fae2001-01-15 00:50:52 +0000824 def help_n(self):
825 print """n(ext)
826Continue execution until the next line in the current function
827is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000828
Tim Peters2344fae2001-01-15 00:50:52 +0000829 def help_return(self):
830 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000831
Tim Peters2344fae2001-01-15 00:50:52 +0000832 def help_r(self):
833 print """r(eturn)
834Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000835
Tim Peters2344fae2001-01-15 00:50:52 +0000836 def help_continue(self):
837 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000838
Tim Peters2344fae2001-01-15 00:50:52 +0000839 def help_cont(self):
840 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000841
Tim Peters2344fae2001-01-15 00:50:52 +0000842 def help_c(self):
843 print """c(ont(inue))
844Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000845
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000846 def help_jump(self):
847 self.help_j()
848
849 def help_j(self):
850 print """j(ump) lineno
851Set the next line that will be executed."""
852
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000853 def help_debug(self):
854 print """debug code
855Enter a recursive debugger that steps through the code argument
856(which is an arbitrary expression or statement to be executed
857in the current environment)."""
858
Tim Peters2344fae2001-01-15 00:50:52 +0000859 def help_list(self):
860 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000861
Tim Peters2344fae2001-01-15 00:50:52 +0000862 def help_l(self):
863 print """l(ist) [first [,last]]
864List source code for the current file.
865Without arguments, list 11 lines around the current line
866or continue the previous listing.
867With one argument, list 11 lines starting at that line.
868With two arguments, list the given range;
869if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000870
Tim Peters2344fae2001-01-15 00:50:52 +0000871 def help_args(self):
872 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000873
Tim Peters2344fae2001-01-15 00:50:52 +0000874 def help_a(self):
875 print """a(rgs)
876Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000877
Tim Peters2344fae2001-01-15 00:50:52 +0000878 def help_p(self):
879 print """p expression
880Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000881
Barry Warsaw210bd202002-11-05 22:40:20 +0000882 def help_pp(self):
883 print """pp expression
884Pretty-print the value of the expression."""
885
Tim Peters2344fae2001-01-15 00:50:52 +0000886 def help_exec(self):
887 print """(!) statement
888Execute the (one-line) statement in the context of
889the current stack frame.
890The exclamation point can be omitted unless the first word
891of the statement resembles a debugger command.
892To assign to a global variable you must always prefix the
893command with a 'global' command, e.g.:
894(Pdb) global list_options; list_options = ['-l']
895(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000896
Tim Peters2344fae2001-01-15 00:50:52 +0000897 def help_quit(self):
898 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000899
Tim Peters2344fae2001-01-15 00:50:52 +0000900 def help_q(self):
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000901 print """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +0000902The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000903
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000904 help_exit = help_q
905
Tim Peters2344fae2001-01-15 00:50:52 +0000906 def help_whatis(self):
907 print """whatis arg
908Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000909
Tim Peters2344fae2001-01-15 00:50:52 +0000910 def help_EOF(self):
911 print """EOF
912Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000913
Tim Peters2344fae2001-01-15 00:50:52 +0000914 def help_alias(self):
915 print """alias [name [command [parameter parameter ...] ]]
916Creates an alias called 'name' the executes 'command'. The command
917must *not* be enclosed in quotes. Replaceable parameters are
918indicated by %1, %2, and so on, while %* is replaced by all the
919parameters. If no command is given, the current alias for name
920is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +0000921
Tim Peters2344fae2001-01-15 00:50:52 +0000922Aliases may be nested and can contain anything that can be
923legally typed at the pdb prompt. Note! You *can* override
924internal pdb commands with aliases! Those internal commands
925are then hidden until the alias is removed. Aliasing is recursively
926applied to the first word of the command line; all other words
927in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +0000928
Tim Peters2344fae2001-01-15 00:50:52 +0000929Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +0000930
Tim Peters2344fae2001-01-15 00:50:52 +0000931#Print instance variables (usage "pi classInst")
932alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +0000933
Tim Peters2344fae2001-01-15 00:50:52 +0000934#Print instance variables in self
935alias ps pi self
936"""
Guido van Rossum2424f851998-09-11 22:50:09 +0000937
Tim Peters2344fae2001-01-15 00:50:52 +0000938 def help_unalias(self):
939 print """unalias name
940Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000941
Tim Peters2344fae2001-01-15 00:50:52 +0000942 def help_pdb(self):
943 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000944
Tim Peters2344fae2001-01-15 00:50:52 +0000945 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000946 """Helper function for break/clear parsing -- may be overridden.
947
948 lookupmodule() translates (possibly incomplete) file or module name
949 into an absolute file name.
950 """
951 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +0000952 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000953 f = os.path.join(sys.path[0], filename)
954 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
955 return f
Tim Peters2344fae2001-01-15 00:50:52 +0000956 root, ext = os.path.splitext(filename)
957 if ext == '':
958 filename = filename + '.py'
959 if os.path.isabs(filename):
960 return filename
961 for dirname in sys.path:
962 while os.path.islink(dirname):
963 dirname = os.readlink(dirname)
964 fullname = os.path.join(dirname, filename)
965 if os.path.exists(fullname):
966 return fullname
967 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +0000968
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000969 def _runscript(self, filename):
970 # Start with fresh empty copy of globals and locals and tell the script
971 # that it's being run as __main__ to avoid scripts being able to access
972 # the pdb.py namespace.
Tim Peterse718f612004-10-12 21:51:32 +0000973 globals_ = {"__name__" : "__main__"}
974 locals_ = globals_
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000975
976 # When bdb sets tracing, a number of call and line events happens
977 # BEFORE debugger even reaches user's code (and the exact sequence of
978 # events depends on python version). So we take special measures to
979 # avoid stopping before we reach the main script (see user_line and
980 # user_call for details).
981 self._wait_for_mainpyfile = 1
982 self.mainpyfile = self.canonic(filename)
983 self._user_requested_quit = 0
984 statement = 'execfile( "%s")' % filename
985 self.run(statement, globals=globals_, locals=locals_)
986
Guido van Rossum35771131992-09-08 11:59:04 +0000987# Simplified interface
988
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000989def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000990 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000991
992def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +0000993 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000994
995def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +0000996 # B/W compatibility
997 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +0000998
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +0000999def runcall(*args, **kwds):
1000 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001001
Guido van Rossumb6775db1994-08-01 11:34:53 +00001002def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001003 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001004
1005# Post-Mortem interface
1006
1007def post_mortem(t):
Tim Peters2344fae2001-01-15 00:50:52 +00001008 p = Pdb()
1009 p.reset()
1010 while t.tb_next is not None:
1011 t = t.tb_next
1012 p.interaction(t.tb_frame, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001013
1014def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001015 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001016
1017
1018# Main program for testing
1019
Guido van Rossum23efba41992-01-27 16:58:47 +00001020TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001021
Guido van Rossum921c8241992-01-10 14:54:42 +00001022def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001023 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001024
1025# print help
1026def help():
Tim Peters2344fae2001-01-15 00:50:52 +00001027 for dirname in sys.path:
1028 fullname = os.path.join(dirname, 'pdb.doc')
1029 if os.path.exists(fullname):
1030 sts = os.system('${PAGER-more} '+fullname)
1031 if sts: print '*** Pager exit status:', sts
1032 break
1033 else:
1034 print 'Sorry, can\'t find the help file "pdb.doc"',
1035 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +00001036
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001037def main():
Tim Peters2344fae2001-01-15 00:50:52 +00001038 if not sys.argv[1:]:
1039 print "usage: pdb.py scriptfile [arg] ..."
1040 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001041
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001042 mainpyfile = sys.argv[1] # Get script filename
1043 if not os.path.exists(mainpyfile):
1044 print 'Error:', mainpyfile, 'does not exist'
Tim Peters2344fae2001-01-15 00:50:52 +00001045 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001046
Tim Peters2344fae2001-01-15 00:50:52 +00001047 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001048
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001049 # Replace pdb's dir with script's dir in front of module search path.
1050 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001051
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001052 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1053 # modified by the script being debugged. It's a bad idea when it was
1054 # changed by the user from the command line. The best approach would be to
1055 # have a "restart" command which would allow explicit specification of
1056 # command line arguments.
1057 pdb = Pdb()
1058 while 1:
1059 try:
1060 pdb._runscript(mainpyfile)
1061 if pdb._user_requested_quit:
1062 break
Tim Peterse718f612004-10-12 21:51:32 +00001063 print "The program finished and will be restarted"
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001064 except SystemExit:
1065 # In most cases SystemExit does not warrant a post-mortem session.
1066 print "The program exited via sys.exit(). Exit status: ",
1067 print sys.exc_info()[1]
1068 except:
1069 traceback.print_exc()
1070 print "Uncaught exception. Entering post mortem debugging"
1071 print "Running 'cont' or 'step' will restart the program"
1072 t = sys.exc_info()[2]
1073 while t.tb_next is not None:
1074 t = t.tb_next
1075 pdb.interaction(t.tb_frame,t)
1076 print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
1077
1078
1079# When invoked as main program, invoke the debugger on a script
1080if __name__=='__main__':
1081 main()