blob: 8b747e714a00cb5bccf5f94e2412ce3d7999d84c [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
Brett Cannon2ee0e8e2008-05-23 05:03:59 +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
Georg Brandl8e84c652007-03-13 21:08:15 +000016
17
18class Restart(Exception):
19 """Causes a debugger to be restarted for the debugged python program."""
20 pass
21
Guido van Rossumef1b41b2002-09-10 21:57:14 +000022# Create a custom safe Repr instance and increase its maxstring.
23# The default of 30 truncates error messages too easily.
24_repr = Repr()
25_repr.maxstring = 200
26_saferepr = _repr.repr
27
Skip Montanaro352674d2001-02-07 23:14:30 +000028__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
29 "post_mortem", "help"]
30
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000031def find_function(funcname, filename):
Andrew M. Kuchlinge6728252006-09-05 13:19:18 +000032 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
Tim Peters2344fae2001-01-15 00:50:52 +000033 try:
34 fp = open(filename)
35 except IOError:
36 return None
37 # consumer of this info expects the first line to be 1
38 lineno = 1
39 answer = None
40 while 1:
41 line = fp.readline()
42 if line == '':
43 break
44 if cre.match(line):
45 answer = funcname, filename, lineno
46 break
47 lineno = lineno + 1
48 fp.close()
49 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +000050
51
Guido van Rossuma558e371994-11-10 22:27:35 +000052# Interaction prompt line will separate file and call info from code
53# text using value of line_prefix string. A newline and arrow may
54# be to your liking. You can set it once pdb is imported using the
55# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +000056# line_prefix = ': ' # Use this to get the old situation back
57line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +000058
Guido van Rossum23efba41992-01-27 16:58:47 +000059class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +000060
Georg Brandl19564802006-05-10 17:13:20 +000061 def __init__(self, completekey='tab', stdin=None, stdout=None):
Tim Peters2344fae2001-01-15 00:50:52 +000062 bdb.Bdb.__init__(self)
Georg Brandl19564802006-05-10 17:13:20 +000063 cmd.Cmd.__init__(self, completekey, stdin, stdout)
64 if stdout:
65 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +000066 self.prompt = '(Pdb) '
67 self.aliases = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +000068 self.mainpyfile = ''
69 self._wait_for_mainpyfile = 0
Tim Peters2344fae2001-01-15 00:50:52 +000070 # Try to load readline if it exists
71 try:
72 import readline
73 except ImportError:
74 pass
Guido van Rossum2424f851998-09-11 22:50:09 +000075
Tim Peters2344fae2001-01-15 00:50:52 +000076 # Read $HOME/.pdbrc and ./.pdbrc
77 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +000078 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +000079 envHome = os.environ['HOME']
80 try:
81 rcFile = open(os.path.join(envHome, ".pdbrc"))
82 except IOError:
83 pass
84 else:
85 for line in rcFile.readlines():
86 self.rcLines.append(line)
87 rcFile.close()
88 try:
89 rcFile = open(".pdbrc")
90 except IOError:
91 pass
92 else:
93 for line in rcFile.readlines():
94 self.rcLines.append(line)
95 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +000096
Martin v. Löwisbd30f522006-04-17 17:08:37 +000097 self.commands = {} # associates a command list to breakpoint numbers
Georg Brandle361bcb2009-04-01 23:32:17 +000098 self.commands_doprompt = {} # for each bp num, tells if the prompt
99 # must be disp. after execing the cmd list
100 self.commands_silent = {} # for each bp num, tells if the stack trace
101 # must be disp. after execing the cmd list
102 self.commands_defining = False # True while in the process of defining
103 # a command list
104 self.commands_bnum = None # The breakpoint number for which we are
105 # defining a list
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000106
Tim Peters2344fae2001-01-15 00:50:52 +0000107 def reset(self):
108 bdb.Bdb.reset(self)
109 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000110
Tim Peters2344fae2001-01-15 00:50:52 +0000111 def forget(self):
112 self.lineno = None
113 self.stack = []
114 self.curindex = 0
115 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +0000116
Tim Peters2344fae2001-01-15 00:50:52 +0000117 def setup(self, f, t):
118 self.forget()
119 self.stack, self.curindex = self.get_stack(f, t)
120 self.curframe = self.stack[self.curindex][0]
Georg Brandle361bcb2009-04-01 23:32:17 +0000121 # The f_locals dictionary is updated from the actual frame
122 # locals whenever the .f_locals accessor is called, so we
123 # cache it here to ensure that modifications are not overwritten.
124 self.curframe_locals = self.curframe.f_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000125 self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000126
Tim Peters2344fae2001-01-15 00:50:52 +0000127 # Can be executed earlier than 'setup' if desired
128 def execRcLines(self):
129 if self.rcLines:
130 # Make local copy because of recursion
131 rcLines = self.rcLines
132 # executed only once
133 self.rcLines = []
134 for line in rcLines:
135 line = line[:-1]
Guido van Rossum08454592002-07-12 13:10:53 +0000136 if len(line) > 0 and line[0] != '#':
137 self.onecmd(line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000138
Tim Peters280488b2002-08-23 18:19:30 +0000139 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000140
141 def user_call(self, frame, argument_list):
142 """This method is called when there is the remote possibility
143 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000144 if self._wait_for_mainpyfile:
145 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000146 if self.stop_here(frame):
Georg Brandl19564802006-05-10 17:13:20 +0000147 print >>self.stdout, '--Call--'
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000148 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000149
Tim Peters2344fae2001-01-15 00:50:52 +0000150 def user_line(self, frame):
151 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000152 if self._wait_for_mainpyfile:
153 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
154 or frame.f_lineno<= 0):
155 return
156 self._wait_for_mainpyfile = 0
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000157 if self.bp_commands(frame):
158 self.interaction(frame, None)
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000159
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000160 def bp_commands(self,frame):
161 """ Call every command that was set for the current active breakpoint (if there is one)
162 Returns True if the normal interaction function must be called, False otherwise """
163 #self.currentbp is set in bdb.py in bdb.break_here if a breakpoint was hit
164 if getattr(self,"currentbp",False) and self.currentbp in self.commands:
165 currentbp = self.currentbp
166 self.currentbp = 0
167 lastcmd_back = self.lastcmd
168 self.setup(frame, None)
169 for line in self.commands[currentbp]:
170 self.onecmd(line)
171 self.lastcmd = lastcmd_back
172 if not self.commands_silent[currentbp]:
173 self.print_stack_entry(self.stack[self.curindex])
174 if self.commands_doprompt[currentbp]:
175 self.cmdloop()
176 self.forget()
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000177 return
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000178 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000179
Tim Peters2344fae2001-01-15 00:50:52 +0000180 def user_return(self, frame, return_value):
181 """This function is called when a return trap is set here."""
182 frame.f_locals['__return__'] = return_value
Georg Brandl19564802006-05-10 17:13:20 +0000183 print >>self.stdout, '--Return--'
Tim Peters2344fae2001-01-15 00:50:52 +0000184 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000185
Brett Cannonc6a30ec2008-08-01 01:36:47 +0000186 def user_exception(self, frame, exc_info):
187 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000188 """This function is called if an exception occurs,
189 but only if we are to stop at or just below this level."""
190 frame.f_locals['__exception__'] = exc_type, exc_value
191 if type(exc_type) == type(''):
192 exc_type_name = exc_type
193 else: exc_type_name = exc_type.__name__
Georg Brandl19564802006-05-10 17:13:20 +0000194 print >>self.stdout, exc_type_name + ':', _saferepr(exc_value)
Tim Peters2344fae2001-01-15 00:50:52 +0000195 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000196
Tim Peters2344fae2001-01-15 00:50:52 +0000197 # General interaction function
198
199 def interaction(self, frame, traceback):
200 self.setup(frame, traceback)
201 self.print_stack_entry(self.stack[self.curindex])
202 self.cmdloop()
203 self.forget()
204
Georg Brandl58b8b952009-04-01 21:54:21 +0000205 def displayhook(self, obj):
206 """Custom displayhook for the exec in default(), which prevents
207 assignment of the _ variable in the builtins.
208 """
209 print obj
210
Tim Peters2344fae2001-01-15 00:50:52 +0000211 def default(self, line):
212 if line[:1] == '!': line = line[1:]
Georg Brandle361bcb2009-04-01 23:32:17 +0000213 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000214 globals = self.curframe.f_globals
215 try:
216 code = compile(line + '\n', '<stdin>', 'single')
Amaury Forgeot d'Arcff0f2672008-01-15 21:25:11 +0000217 save_stdout = sys.stdout
218 save_stdin = sys.stdin
Georg Brandl58b8b952009-04-01 21:54:21 +0000219 save_displayhook = sys.displayhook
Guido van Rossumcad37242008-01-15 17:59:29 +0000220 try:
221 sys.stdin = self.stdin
222 sys.stdout = self.stdout
Georg Brandl58b8b952009-04-01 21:54:21 +0000223 sys.displayhook = self.displayhook
Guido van Rossumcad37242008-01-15 17:59:29 +0000224 exec code in globals, locals
225 finally:
226 sys.stdout = save_stdout
227 sys.stdin = save_stdin
Georg Brandl58b8b952009-04-01 21:54:21 +0000228 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000229 except:
230 t, v = sys.exc_info()[:2]
231 if type(t) == type(''):
232 exc_type_name = t
233 else: exc_type_name = t.__name__
Georg Brandl19564802006-05-10 17:13:20 +0000234 print >>self.stdout, '***', exc_type_name + ':', v
Tim Peters2344fae2001-01-15 00:50:52 +0000235
236 def precmd(self, line):
237 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000238 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000239 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000240 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000241 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000242 line = self.aliases[args[0]]
243 ii = 1
244 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000245 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000246 tmpArg)
247 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000248 line = line.replace("%*", ' '.join(args[1:]))
249 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000250 # split into ';;' separated commands
251 # unless it's an alias command
252 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000253 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000254 if marker >= 0:
255 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000256 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000257 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000258 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000259 return line
260
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000261 def onecmd(self, line):
262 """Interpret the argument as though it had been typed in response
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000263 to the prompt.
264
Andrew M. Kuchling9aed98f2006-07-27 12:18:20 +0000265 Checks whether this line is typed at the normal prompt or in
Tim Petersdaea0352006-07-27 15:11:00 +0000266 a breakpoint command list definition.
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000267 """
268 if not self.commands_defining:
269 return cmd.Cmd.onecmd(self, line)
270 else:
271 return self.handle_command_def(line)
272
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000273 def handle_command_def(self,line):
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000274 """ Handles one command line during command list definition. """
275 cmd, arg, line = self.parseline(line)
276 if cmd == 'silent':
277 self.commands_silent[self.commands_bnum] = True
278 return # continue to handle other cmd def in the cmd list
279 elif cmd == 'end':
280 self.cmdqueue = []
281 return 1 # end of cmd list
282 cmdlist = self.commands[self.commands_bnum]
283 if (arg):
284 cmdlist.append(cmd+' '+arg)
285 else:
286 cmdlist.append(cmd)
287 # Determine if we must stop
288 try:
289 func = getattr(self, 'do_' + cmd)
290 except AttributeError:
291 func = self.default
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000292 if func.func_name in self.commands_resuming : # one of the resuming commands.
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000293 self.commands_doprompt[self.commands_bnum] = False
294 self.cmdqueue = []
295 return 1
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000296 return
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000297
Tim Peters2344fae2001-01-15 00:50:52 +0000298 # Command definitions, called by cmdloop()
299 # The argument is the remaining string on the command line
300 # Return true to exit from the command loop
301
302 do_h = cmd.Cmd.do_help
303
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000304 def do_commands(self, arg):
305 """Defines a list of commands associated to a breakpoint
306 Those commands will be executed whenever the breakpoint causes the program to stop execution."""
307 if not arg:
308 bnum = len(bdb.Breakpoint.bpbynumber)-1
309 else:
310 try:
311 bnum = int(arg)
312 except:
Georg Brandl19564802006-05-10 17:13:20 +0000313 print >>self.stdout, "Usage : commands [bnum]\n ...\n end"
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000314 return
315 self.commands_bnum = bnum
316 self.commands[bnum] = []
317 self.commands_doprompt[bnum] = True
318 self.commands_silent[bnum] = False
319 prompt_back = self.prompt
320 self.prompt = '(com) '
321 self.commands_defining = True
322 self.cmdloop()
323 self.commands_defining = False
324 self.prompt = prompt_back
325
Tim Peters2344fae2001-01-15 00:50:52 +0000326 def do_break(self, arg, temporary = 0):
327 # break [ ([filename:]lineno | function) [, "condition"] ]
328 if not arg:
329 if self.breaks: # There's at least one
Georg Brandl19564802006-05-10 17:13:20 +0000330 print >>self.stdout, "Num Type Disp Enb Where"
Tim Peters2344fae2001-01-15 00:50:52 +0000331 for bp in bdb.Breakpoint.bpbynumber:
332 if bp:
Georg Brandl19564802006-05-10 17:13:20 +0000333 bp.bpprint(self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000334 return
335 # parse arguments; comma has lowest precedence
336 # and cannot occur in filename
337 filename = None
338 lineno = None
339 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000340 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000341 if comma > 0:
342 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000343 cond = arg[comma+1:].lstrip()
344 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000345 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000346 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000347 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000348 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000349 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000350 f = self.lookupmodule(filename)
351 if not f:
Georg Brandl19564802006-05-10 17:13:20 +0000352 print >>self.stdout, '*** ', repr(filename),
353 print >>self.stdout, 'not found from sys.path'
Tim Peters2344fae2001-01-15 00:50:52 +0000354 return
355 else:
356 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000357 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000358 try:
359 lineno = int(arg)
360 except ValueError, msg:
Georg Brandl19564802006-05-10 17:13:20 +0000361 print >>self.stdout, '*** Bad lineno:', arg
Tim Peters2344fae2001-01-15 00:50:52 +0000362 return
363 else:
364 # no colon; can be lineno or function
365 try:
366 lineno = int(arg)
367 except ValueError:
368 try:
369 func = eval(arg,
370 self.curframe.f_globals,
Georg Brandle361bcb2009-04-01 23:32:17 +0000371 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000372 except:
373 func = arg
374 try:
375 if hasattr(func, 'im_func'):
376 func = func.im_func
377 code = func.func_code
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000378 #use co_name to identify the bkpt (function names
379 #could be aliased, but co_name is invariant)
380 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000381 lineno = code.co_firstlineno
382 filename = code.co_filename
383 except:
384 # last thing to try
385 (ok, filename, ln) = self.lineinfo(arg)
386 if not ok:
Georg Brandl19564802006-05-10 17:13:20 +0000387 print >>self.stdout, '*** The specified object',
388 print >>self.stdout, repr(arg),
389 print >>self.stdout, 'is not a function'
390 print >>self.stdout, 'or was not found along sys.path.'
Tim Peters2344fae2001-01-15 00:50:52 +0000391 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000392 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000393 lineno = int(ln)
394 if not filename:
395 filename = self.defaultFile()
396 # Check for reasonable breakpoint
397 line = self.checkline(filename, lineno)
398 if line:
399 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000400 err = self.set_break(filename, line, temporary, cond, funcname)
Georg Brandl19564802006-05-10 17:13:20 +0000401 if err: print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000402 else:
403 bp = self.get_breaks(filename, line)[-1]
Georg Brandl19564802006-05-10 17:13:20 +0000404 print >>self.stdout, "Breakpoint %d at %s:%d" % (bp.number,
405 bp.file,
406 bp.line)
Tim Peters2344fae2001-01-15 00:50:52 +0000407
408 # To be overridden in derived debuggers
409 def defaultFile(self):
410 """Produce a reasonable default."""
411 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000412 if filename == '<string>' and self.mainpyfile:
413 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000414 return filename
415
416 do_b = do_break
417
418 def do_tbreak(self, arg):
419 self.do_break(arg, 1)
420
421 def lineinfo(self, identifier):
422 failed = (None, None, None)
423 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000424 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000425 if len(idstring) == 1:
426 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000427 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000428 elif len(idstring) == 3:
429 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000430 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000431 else:
432 return failed
433 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000434 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000435 # Protection for derived debuggers
436 if parts[0] == 'self':
437 del parts[0]
438 if len(parts) == 0:
439 return failed
440 # Best first guess at file to look at
441 fname = self.defaultFile()
442 if len(parts) == 1:
443 item = parts[0]
444 else:
445 # More than one part.
446 # First is module, second is method/class
447 f = self.lookupmodule(parts[0])
448 if f:
449 fname = f
450 item = parts[1]
451 answer = find_function(item, fname)
452 return answer or failed
453
454 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000455 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000456
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000457 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
458 line or EOF). Warning: testing is not comprehensive.
459 """
Nick Coghlana2053472008-12-14 10:54:50 +0000460 line = linecache.getline(filename, lineno, self.curframe.f_globals)
Tim Peters2344fae2001-01-15 00:50:52 +0000461 if not line:
Georg Brandl19564802006-05-10 17:13:20 +0000462 print >>self.stdout, 'End of file'
Tim Peters2344fae2001-01-15 00:50:52 +0000463 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000464 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000465 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000466 if (not line or (line[0] == '#') or
467 (line[:3] == '"""') or line[:3] == "'''"):
Georg Brandl19564802006-05-10 17:13:20 +0000468 print >>self.stdout, '*** Blank or comment'
Tim Peters2344fae2001-01-15 00:50:52 +0000469 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000470 return lineno
471
472 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000473 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000474 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000475 try:
476 i = int(i)
477 except ValueError:
Georg Brandl19564802006-05-10 17:13:20 +0000478 print >>self.stdout, 'Breakpoint index %r is not a number' % i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000479 continue
480
481 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Georg Brandl19564802006-05-10 17:13:20 +0000482 print >>self.stdout, 'No breakpoint numbered', i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000483 continue
484
485 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000486 if bp:
487 bp.enable()
488
489 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000490 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000491 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000492 try:
493 i = int(i)
494 except ValueError:
Georg Brandl19564802006-05-10 17:13:20 +0000495 print >>self.stdout, 'Breakpoint index %r is not a number' % i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000496 continue
Tim Petersf545baa2003-06-15 23:26:30 +0000497
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000498 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Georg Brandl19564802006-05-10 17:13:20 +0000499 print >>self.stdout, 'No breakpoint numbered', i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000500 continue
501
502 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000503 if bp:
504 bp.disable()
505
506 def do_condition(self, arg):
507 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000508 args = arg.split(' ', 1)
Georg Brandle4980832007-01-22 21:23:41 +0000509 try:
510 bpnum = int(args[0].strip())
511 except ValueError:
512 # something went wrong
513 print >>self.stdout, \
514 'Breakpoint index %r is not a number' % args[0]
Georg Brandlb2783182007-03-11 08:28:46 +0000515 return
Tim Peters2344fae2001-01-15 00:50:52 +0000516 try:
517 cond = args[1]
518 except:
519 cond = None
Collin Winter2faa9e12007-03-11 16:00:20 +0000520 try:
521 bp = bdb.Breakpoint.bpbynumber[bpnum]
522 except IndexError:
523 print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
524 return
Tim Peters2344fae2001-01-15 00:50:52 +0000525 if bp:
526 bp.cond = cond
527 if not cond:
Georg Brandl19564802006-05-10 17:13:20 +0000528 print >>self.stdout, 'Breakpoint', bpnum,
529 print >>self.stdout, 'is now unconditional.'
Tim Peters2344fae2001-01-15 00:50:52 +0000530
531 def do_ignore(self,arg):
532 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000533 args = arg.split()
Georg Brandle4980832007-01-22 21:23:41 +0000534 try:
535 bpnum = int(args[0].strip())
536 except ValueError:
537 # something went wrong
538 print >>self.stdout, \
539 'Breakpoint index %r is not a number' % args[0]
Georg Brandlb2783182007-03-11 08:28:46 +0000540 return
Tim Peters2344fae2001-01-15 00:50:52 +0000541 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000542 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000543 except:
544 count = 0
Collin Winter2faa9e12007-03-11 16:00:20 +0000545 try:
546 bp = bdb.Breakpoint.bpbynumber[bpnum]
547 except IndexError:
548 print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
549 return
Tim Peters2344fae2001-01-15 00:50:52 +0000550 if bp:
551 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000552 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000553 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000554 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000555 reply = reply + '%d crossings' % count
556 else:
557 reply = reply + '1 crossing'
Georg Brandl19564802006-05-10 17:13:20 +0000558 print >>self.stdout, reply + ' of breakpoint %d.' % bpnum
Tim Peters2344fae2001-01-15 00:50:52 +0000559 else:
Georg Brandl19564802006-05-10 17:13:20 +0000560 print >>self.stdout, 'Will stop next time breakpoint',
561 print >>self.stdout, bpnum, 'is reached.'
Tim Peters2344fae2001-01-15 00:50:52 +0000562
563 def do_clear(self, arg):
564 """Three possibilities, tried in this order:
565 clear -> clear all breaks, ask for confirmation
566 clear file:lineno -> clear all breaks at file:lineno
567 clear bpno bpno ... -> clear breakpoints by number"""
568 if not arg:
569 try:
570 reply = raw_input('Clear all breaks? ')
571 except EOFError:
572 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000573 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000574 if reply in ('y', 'yes'):
575 self.clear_all_breaks()
576 return
577 if ':' in arg:
578 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000579 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000580 filename = arg[:i]
581 arg = arg[i+1:]
582 try:
583 lineno = int(arg)
Georg Brandl23d9d452006-05-03 18:12:33 +0000584 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000585 err = "Invalid line number (%s)" % arg
586 else:
587 err = self.clear_break(filename, lineno)
Georg Brandl19564802006-05-10 17:13:20 +0000588 if err: print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000589 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000590 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000591 for i in numberlist:
Georg Brandl23d9d452006-05-03 18:12:33 +0000592 try:
593 i = int(i)
594 except ValueError:
Georg Brandl19564802006-05-10 17:13:20 +0000595 print >>self.stdout, 'Breakpoint index %r is not a number' % i
Georg Brandl23d9d452006-05-03 18:12:33 +0000596 continue
597
Georg Brandl6d2b3462005-08-24 07:36:17 +0000598 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Georg Brandl19564802006-05-10 17:13:20 +0000599 print >>self.stdout, 'No breakpoint numbered', i
Georg Brandl6d2b3462005-08-24 07:36:17 +0000600 continue
Tim Peters2344fae2001-01-15 00:50:52 +0000601 err = self.clear_bpbynumber(i)
602 if err:
Georg Brandl19564802006-05-10 17:13:20 +0000603 print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000604 else:
Georg Brandl19564802006-05-10 17:13:20 +0000605 print >>self.stdout, 'Deleted breakpoint', i
Tim Peters2344fae2001-01-15 00:50:52 +0000606 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
607
608 def do_where(self, arg):
609 self.print_stack_trace()
610 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000611 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000612
613 def do_up(self, arg):
614 if self.curindex == 0:
Georg Brandl19564802006-05-10 17:13:20 +0000615 print >>self.stdout, '*** Oldest frame'
Tim Peters2344fae2001-01-15 00:50:52 +0000616 else:
617 self.curindex = self.curindex - 1
618 self.curframe = self.stack[self.curindex][0]
619 self.print_stack_entry(self.stack[self.curindex])
620 self.lineno = None
621 do_u = do_up
622
623 def do_down(self, arg):
624 if self.curindex + 1 == len(self.stack):
Georg Brandl19564802006-05-10 17:13:20 +0000625 print >>self.stdout, '*** Newest frame'
Tim Peters2344fae2001-01-15 00:50:52 +0000626 else:
627 self.curindex = self.curindex + 1
628 self.curframe = self.stack[self.curindex][0]
629 self.print_stack_entry(self.stack[self.curindex])
630 self.lineno = None
631 do_d = do_down
632
Benjamin Peterson98353942008-05-11 14:13:25 +0000633 def do_until(self, arg):
634 self.set_until(self.curframe)
635 return 1
636 do_unt = do_until
637
Tim Peters2344fae2001-01-15 00:50:52 +0000638 def do_step(self, arg):
639 self.set_step()
640 return 1
641 do_s = do_step
642
643 def do_next(self, arg):
644 self.set_next(self.curframe)
645 return 1
646 do_n = do_next
647
Georg Brandl8e84c652007-03-13 21:08:15 +0000648 def do_run(self, arg):
649 """Restart program by raising an exception to be caught in the main debugger
650 loop. If arguments were given, set them in sys.argv."""
651 if arg:
652 import shlex
653 argv0 = sys.argv[0:1]
654 sys.argv = shlex.split(arg)
655 sys.argv[:0] = argv0
656 raise Restart
657
658 do_restart = do_run
659
Tim Peters2344fae2001-01-15 00:50:52 +0000660 def do_return(self, arg):
661 self.set_return(self.curframe)
662 return 1
663 do_r = do_return
664
665 def do_continue(self, arg):
666 self.set_continue()
667 return 1
668 do_c = do_cont = do_continue
669
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000670 def do_jump(self, arg):
671 if self.curindex + 1 != len(self.stack):
Georg Brandl19564802006-05-10 17:13:20 +0000672 print >>self.stdout, "*** You can only jump within the bottom frame"
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000673 return
674 try:
675 arg = int(arg)
676 except ValueError:
Georg Brandl19564802006-05-10 17:13:20 +0000677 print >>self.stdout, "*** The 'jump' command requires a line number."
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000678 else:
679 try:
680 # Do the jump, fix up our copy of the stack, and display the
681 # new position
682 self.curframe.f_lineno = arg
683 self.stack[self.curindex] = self.stack[self.curindex][0], arg
684 self.print_stack_entry(self.stack[self.curindex])
685 except ValueError, e:
Georg Brandl19564802006-05-10 17:13:20 +0000686 print >>self.stdout, '*** Jump failed:', e
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000687 do_j = do_jump
688
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000689 def do_debug(self, arg):
690 sys.settrace(None)
691 globals = self.curframe.f_globals
Georg Brandle361bcb2009-04-01 23:32:17 +0000692 locals = self.curframe_locals
Guido van Rossumcad37242008-01-15 17:59:29 +0000693 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +0000694 p.prompt = "(%s) " % self.prompt.strip()
Georg Brandl19564802006-05-10 17:13:20 +0000695 print >>self.stdout, "ENTERING RECURSIVE DEBUGGER"
Guido van Rossumed538d82003-04-09 19:36:34 +0000696 sys.call_tracing(p.run, (arg, globals, locals))
Georg Brandl19564802006-05-10 17:13:20 +0000697 print >>self.stdout, "LEAVING RECURSIVE DEBUGGER"
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000698 sys.settrace(self.trace_dispatch)
699 self.lastcmd = p.lastcmd
700
Tim Peters2344fae2001-01-15 00:50:52 +0000701 def do_quit(self, arg):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000702 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000703 self.set_quit()
704 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000705
Tim Peters2344fae2001-01-15 00:50:52 +0000706 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000707 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000708
Guido van Rossumeef26072003-01-13 21:13:55 +0000709 def do_EOF(self, arg):
Georg Brandl19564802006-05-10 17:13:20 +0000710 print >>self.stdout
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000711 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000712 self.set_quit()
713 return 1
714
Tim Peters2344fae2001-01-15 00:50:52 +0000715 def do_args(self, arg):
Georg Brandle361bcb2009-04-01 23:32:17 +0000716 co = self.curframe.f_code
717 dict = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000718 n = co.co_argcount
719 if co.co_flags & 4: n = n+1
720 if co.co_flags & 8: n = n+1
721 for i in range(n):
722 name = co.co_varnames[i]
Georg Brandl19564802006-05-10 17:13:20 +0000723 print >>self.stdout, name, '=',
724 if name in dict: print >>self.stdout, dict[name]
725 else: print >>self.stdout, "*** undefined ***"
Tim Peters2344fae2001-01-15 00:50:52 +0000726 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000727
Tim Peters2344fae2001-01-15 00:50:52 +0000728 def do_retval(self, arg):
Georg Brandle361bcb2009-04-01 23:32:17 +0000729 if '__return__' in self.curframe_locals:
730 print >>self.stdout, self.curframe_locals['__return__']
Tim Peters2344fae2001-01-15 00:50:52 +0000731 else:
Georg Brandl19564802006-05-10 17:13:20 +0000732 print >>self.stdout, '*** Not yet returned!'
Tim Peters2344fae2001-01-15 00:50:52 +0000733 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000734
Barry Warsaw210bd202002-11-05 22:40:20 +0000735 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000736 try:
Barry Warsaw210bd202002-11-05 22:40:20 +0000737 return eval(arg, self.curframe.f_globals,
Georg Brandle361bcb2009-04-01 23:32:17 +0000738 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000739 except:
740 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000741 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000742 exc_type_name = t
743 else: exc_type_name = t.__name__
Georg Brandl19564802006-05-10 17:13:20 +0000744 print >>self.stdout, '***', exc_type_name + ':', repr(v)
Barry Warsaw210bd202002-11-05 22:40:20 +0000745 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000746
Barry Warsaw210bd202002-11-05 22:40:20 +0000747 def do_p(self, arg):
748 try:
Georg Brandl19564802006-05-10 17:13:20 +0000749 print >>self.stdout, repr(self._getval(arg))
Barry Warsaw210bd202002-11-05 22:40:20 +0000750 except:
751 pass
752
753 def do_pp(self, arg):
754 try:
Georg Brandl19564802006-05-10 17:13:20 +0000755 pprint.pprint(self._getval(arg), self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +0000756 except:
757 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000758
Tim Peters2344fae2001-01-15 00:50:52 +0000759 def do_list(self, arg):
760 self.lastcmd = 'list'
761 last = None
762 if arg:
763 try:
764 x = eval(arg, {}, {})
765 if type(x) == type(()):
766 first, last = x
767 first = int(first)
768 last = int(last)
769 if last < first:
770 # Assume it's a count
771 last = first + last
772 else:
773 first = max(1, int(x) - 5)
774 except:
Georg Brandl19564802006-05-10 17:13:20 +0000775 print >>self.stdout, '*** Error in argument:', repr(arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000776 return
777 elif self.lineno is None:
778 first = max(1, self.curframe.f_lineno - 5)
779 else:
780 first = self.lineno + 1
781 if last is None:
782 last = first + 10
783 filename = self.curframe.f_code.co_filename
784 breaklist = self.get_file_breaks(filename)
785 try:
786 for lineno in range(first, last+1):
Nick Coghlana2053472008-12-14 10:54:50 +0000787 line = linecache.getline(filename, lineno, self.curframe.f_globals)
Tim Peters2344fae2001-01-15 00:50:52 +0000788 if not line:
Georg Brandl19564802006-05-10 17:13:20 +0000789 print >>self.stdout, '[EOF]'
Tim Peters2344fae2001-01-15 00:50:52 +0000790 break
791 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000792 s = repr(lineno).rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000793 if len(s) < 4: s = s + ' '
794 if lineno in breaklist: s = s + 'B'
795 else: s = s + ' '
796 if lineno == self.curframe.f_lineno:
797 s = s + '->'
Georg Brandl19564802006-05-10 17:13:20 +0000798 print >>self.stdout, s + '\t' + line,
Tim Peters2344fae2001-01-15 00:50:52 +0000799 self.lineno = lineno
800 except KeyboardInterrupt:
801 pass
802 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000803
Tim Peters2344fae2001-01-15 00:50:52 +0000804 def do_whatis(self, arg):
805 try:
806 value = eval(arg, self.curframe.f_globals,
Georg Brandle361bcb2009-04-01 23:32:17 +0000807 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000808 except:
809 t, v = sys.exc_info()[:2]
810 if type(t) == type(''):
811 exc_type_name = t
812 else: exc_type_name = t.__name__
Georg Brandl19564802006-05-10 17:13:20 +0000813 print >>self.stdout, '***', exc_type_name + ':', repr(v)
Tim Peters2344fae2001-01-15 00:50:52 +0000814 return
815 code = None
816 # Is it a function?
817 try: code = value.func_code
818 except: pass
819 if code:
Georg Brandl19564802006-05-10 17:13:20 +0000820 print >>self.stdout, 'Function', code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000821 return
822 # Is it an instance method?
823 try: code = value.im_func.func_code
824 except: pass
825 if code:
Georg Brandl19564802006-05-10 17:13:20 +0000826 print >>self.stdout, 'Method', code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000827 return
828 # None of the above...
Georg Brandl19564802006-05-10 17:13:20 +0000829 print >>self.stdout, type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000830
Tim Peters2344fae2001-01-15 00:50:52 +0000831 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000832 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000833 if len(args) == 0:
834 keys = self.aliases.keys()
835 keys.sort()
836 for alias in keys:
Georg Brandl19564802006-05-10 17:13:20 +0000837 print >>self.stdout, "%s = %s" % (alias, self.aliases[alias])
Tim Peters2344fae2001-01-15 00:50:52 +0000838 return
Guido van Rossum08454592002-07-12 13:10:53 +0000839 if args[0] in self.aliases and len(args) == 1:
Georg Brandl19564802006-05-10 17:13:20 +0000840 print >>self.stdout, "%s = %s" % (args[0], self.aliases[args[0]])
Tim Peters2344fae2001-01-15 00:50:52 +0000841 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000842 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000843
Tim Peters2344fae2001-01-15 00:50:52 +0000844 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000845 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000846 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000847 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000848 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000849
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000850 #list of all the commands making the program resume execution.
Georg Brandl19564802006-05-10 17:13:20 +0000851 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
852 'do_quit', 'do_jump']
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000853
Tim Peters2344fae2001-01-15 00:50:52 +0000854 # Print a traceback starting at the top stack frame.
855 # The most recently entered frame is printed last;
856 # this is different from dbx and gdb, but consistent with
857 # the Python interpreter's stack trace.
858 # It is also consistent with the up/down commands (which are
859 # compatible with dbx and gdb: up moves towards 'main()'
860 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000861
Tim Peters2344fae2001-01-15 00:50:52 +0000862 def print_stack_trace(self):
863 try:
864 for frame_lineno in self.stack:
865 self.print_stack_entry(frame_lineno)
866 except KeyboardInterrupt:
867 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000868
Tim Peters2344fae2001-01-15 00:50:52 +0000869 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
870 frame, lineno = frame_lineno
871 if frame is self.curframe:
Georg Brandl19564802006-05-10 17:13:20 +0000872 print >>self.stdout, '>',
Tim Peters2344fae2001-01-15 00:50:52 +0000873 else:
Georg Brandl19564802006-05-10 17:13:20 +0000874 print >>self.stdout, ' ',
875 print >>self.stdout, self.format_stack_entry(frame_lineno,
876 prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000877
Guido van Rossum921c8241992-01-10 14:54:42 +0000878
Tim Peters2344fae2001-01-15 00:50:52 +0000879 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000880
Tim Peters2344fae2001-01-15 00:50:52 +0000881 def help_help(self):
882 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000883
Tim Peters2344fae2001-01-15 00:50:52 +0000884 def help_h(self):
Georg Brandl19564802006-05-10 17:13:20 +0000885 print >>self.stdout, """h(elp)
Tim Peters2344fae2001-01-15 00:50:52 +0000886Without argument, print the list of available commands.
887With a command name as argument, print help about that command
888"help pdb" pipes the full documentation file to the $PAGER
889"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000890
Tim Peters2344fae2001-01-15 00:50:52 +0000891 def help_where(self):
892 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000893
Tim Peters2344fae2001-01-15 00:50:52 +0000894 def help_w(self):
Georg Brandl19564802006-05-10 17:13:20 +0000895 print >>self.stdout, """w(here)
Tim Peters2344fae2001-01-15 00:50:52 +0000896Print a stack trace, with the most recent frame at the bottom.
897An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000898context of most commands. 'bt' is an alias for this command."""
899
900 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000901
Tim Peters2344fae2001-01-15 00:50:52 +0000902 def help_down(self):
903 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000904
Tim Peters2344fae2001-01-15 00:50:52 +0000905 def help_d(self):
Georg Brandl19564802006-05-10 17:13:20 +0000906 print >>self.stdout, """d(own)
Tim Peters2344fae2001-01-15 00:50:52 +0000907Move the current frame one level down in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000908(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000909
Tim Peters2344fae2001-01-15 00:50:52 +0000910 def help_up(self):
911 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000912
Tim Peters2344fae2001-01-15 00:50:52 +0000913 def help_u(self):
Georg Brandl19564802006-05-10 17:13:20 +0000914 print >>self.stdout, """u(p)
Tim Peters2344fae2001-01-15 00:50:52 +0000915Move the current frame one level up in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000916(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000917
Tim Peters2344fae2001-01-15 00:50:52 +0000918 def help_break(self):
919 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000920
Tim Peters2344fae2001-01-15 00:50:52 +0000921 def help_b(self):
Georg Brandl19564802006-05-10 17:13:20 +0000922 print >>self.stdout, """b(reak) ([file:]lineno | function) [, condition]
Tim Peters2344fae2001-01-15 00:50:52 +0000923With a line number argument, set a break there in the current
924file. With a function name, set a break at first executable line
925of that function. Without argument, list all breaks. If a second
926argument is present, it is a string specifying an expression
927which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000928
Tim Peters2344fae2001-01-15 00:50:52 +0000929The line number may be prefixed with a filename and a colon,
930to specify a breakpoint in another file (probably one that
931hasn't been loaded yet). The file is searched for on sys.path;
932the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000933
Tim Peters2344fae2001-01-15 00:50:52 +0000934 def help_clear(self):
935 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000936
Tim Peters2344fae2001-01-15 00:50:52 +0000937 def help_cl(self):
Georg Brandl19564802006-05-10 17:13:20 +0000938 print >>self.stdout, "cl(ear) filename:lineno"
939 print >>self.stdout, """cl(ear) [bpnumber [bpnumber...]]
Tim Peters2344fae2001-01-15 00:50:52 +0000940With a space separated list of breakpoint numbers, clear
941those breakpoints. Without argument, clear all breaks (but
942first ask confirmation). With a filename:lineno argument,
943clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000944
Tim Peters2344fae2001-01-15 00:50:52 +0000945Note that the argument is different from previous versions of
946the debugger (in python distributions 1.5.1 and before) where
947a linenumber was used instead of either filename:lineno or
948breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000949
Tim Peters2344fae2001-01-15 00:50:52 +0000950 def help_tbreak(self):
Georg Brandl19564802006-05-10 17:13:20 +0000951 print >>self.stdout, """tbreak same arguments as break, but breakpoint is
Tim Peters2344fae2001-01-15 00:50:52 +0000952removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000953
Tim Peters2344fae2001-01-15 00:50:52 +0000954 def help_enable(self):
Georg Brandl19564802006-05-10 17:13:20 +0000955 print >>self.stdout, """enable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +0000956Enables the breakpoints given as a space separated list of
957bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000958
Tim Peters2344fae2001-01-15 00:50:52 +0000959 def help_disable(self):
Georg Brandl19564802006-05-10 17:13:20 +0000960 print >>self.stdout, """disable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +0000961Disables the breakpoints given as a space separated list of
962bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000963
Tim Peters2344fae2001-01-15 00:50:52 +0000964 def help_ignore(self):
Georg Brandl19564802006-05-10 17:13:20 +0000965 print >>self.stdout, """ignore bpnumber count
Tim Peters2344fae2001-01-15 00:50:52 +0000966Sets the ignore count for the given breakpoint number. A breakpoint
967becomes active when the ignore count is zero. When non-zero, the
968count is decremented each time the breakpoint is reached and the
969breakpoint is not disabled and any associated condition evaluates
970to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000971
Tim Peters2344fae2001-01-15 00:50:52 +0000972 def help_condition(self):
Georg Brandl19564802006-05-10 17:13:20 +0000973 print >>self.stdout, """condition bpnumber str_condition
Tim Peters2344fae2001-01-15 00:50:52 +0000974str_condition is a string specifying an expression which
975must evaluate to true before the breakpoint is honored.
976If str_condition is absent, any existing condition is removed;
977i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000978
Tim Peters2344fae2001-01-15 00:50:52 +0000979 def help_step(self):
980 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000981
Tim Peters2344fae2001-01-15 00:50:52 +0000982 def help_s(self):
Georg Brandl19564802006-05-10 17:13:20 +0000983 print >>self.stdout, """s(tep)
Tim Peters2344fae2001-01-15 00:50:52 +0000984Execute the current line, stop at the first possible occasion
985(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000986
Benjamin Peterson98353942008-05-11 14:13:25 +0000987 def help_until(self):
988 self.help_unt()
989
990 def help_unt(self):
991 print """unt(il)
992Continue execution until the line with a number greater than the current
993one is reached or until the current frame returns"""
994
Tim Peters2344fae2001-01-15 00:50:52 +0000995 def help_next(self):
996 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000997
Tim Peters2344fae2001-01-15 00:50:52 +0000998 def help_n(self):
Georg Brandl19564802006-05-10 17:13:20 +0000999 print >>self.stdout, """n(ext)
Tim Peters2344fae2001-01-15 00:50:52 +00001000Continue execution until the next line in the current function
1001is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001002
Tim Peters2344fae2001-01-15 00:50:52 +00001003 def help_return(self):
1004 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001005
Tim Peters2344fae2001-01-15 00:50:52 +00001006 def help_r(self):
Georg Brandl19564802006-05-10 17:13:20 +00001007 print >>self.stdout, """r(eturn)
Tim Peters2344fae2001-01-15 00:50:52 +00001008Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001009
Tim Peters2344fae2001-01-15 00:50:52 +00001010 def help_continue(self):
1011 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001012
Tim Peters2344fae2001-01-15 00:50:52 +00001013 def help_cont(self):
1014 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001015
Tim Peters2344fae2001-01-15 00:50:52 +00001016 def help_c(self):
Georg Brandl19564802006-05-10 17:13:20 +00001017 print >>self.stdout, """c(ont(inue))
Tim Peters2344fae2001-01-15 00:50:52 +00001018Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001019
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001020 def help_jump(self):
1021 self.help_j()
1022
1023 def help_j(self):
Georg Brandl19564802006-05-10 17:13:20 +00001024 print >>self.stdout, """j(ump) lineno
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001025Set the next line that will be executed."""
1026
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001027 def help_debug(self):
Georg Brandl19564802006-05-10 17:13:20 +00001028 print >>self.stdout, """debug code
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001029Enter a recursive debugger that steps through the code argument
1030(which is an arbitrary expression or statement to be executed
1031in the current environment)."""
1032
Tim Peters2344fae2001-01-15 00:50:52 +00001033 def help_list(self):
1034 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001035
Tim Peters2344fae2001-01-15 00:50:52 +00001036 def help_l(self):
Georg Brandl19564802006-05-10 17:13:20 +00001037 print >>self.stdout, """l(ist) [first [,last]]
Tim Peters2344fae2001-01-15 00:50:52 +00001038List source code for the current file.
1039Without arguments, list 11 lines around the current line
1040or continue the previous listing.
1041With one argument, list 11 lines starting at that line.
1042With two arguments, list the given range;
1043if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001044
Tim Peters2344fae2001-01-15 00:50:52 +00001045 def help_args(self):
1046 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001047
Tim Peters2344fae2001-01-15 00:50:52 +00001048 def help_a(self):
Georg Brandl19564802006-05-10 17:13:20 +00001049 print >>self.stdout, """a(rgs)
Tim Peters2344fae2001-01-15 00:50:52 +00001050Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001051
Tim Peters2344fae2001-01-15 00:50:52 +00001052 def help_p(self):
Georg Brandl19564802006-05-10 17:13:20 +00001053 print >>self.stdout, """p expression
Tim Peters2344fae2001-01-15 00:50:52 +00001054Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001055
Barry Warsaw210bd202002-11-05 22:40:20 +00001056 def help_pp(self):
Georg Brandl19564802006-05-10 17:13:20 +00001057 print >>self.stdout, """pp expression
Barry Warsaw210bd202002-11-05 22:40:20 +00001058Pretty-print the value of the expression."""
1059
Tim Peters2344fae2001-01-15 00:50:52 +00001060 def help_exec(self):
Georg Brandl19564802006-05-10 17:13:20 +00001061 print >>self.stdout, """(!) statement
Tim Peters2344fae2001-01-15 00:50:52 +00001062Execute the (one-line) statement in the context of
1063the current stack frame.
1064The exclamation point can be omitted unless the first word
1065of the statement resembles a debugger command.
1066To assign to a global variable you must always prefix the
1067command with a 'global' command, e.g.:
1068(Pdb) global list_options; list_options = ['-l']
1069(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001070
Georg Brandl8e84c652007-03-13 21:08:15 +00001071 def help_run(self):
1072 print """run [args...]
1073Restart the debugged python program. If a string is supplied, it is
1074splitted with "shlex" and the result is used as the new sys.argv.
1075History, breakpoints, actions and debugger options are preserved.
1076"restart" is an alias for "run"."""
1077
1078 help_restart = help_run
1079
Tim Peters2344fae2001-01-15 00:50:52 +00001080 def help_quit(self):
1081 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001082
Tim Peters2344fae2001-01-15 00:50:52 +00001083 def help_q(self):
Georg Brandl19564802006-05-10 17:13:20 +00001084 print >>self.stdout, """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +00001085The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001086
Guido van Rossumd1c08f32002-04-15 00:48:24 +00001087 help_exit = help_q
1088
Tim Peters2344fae2001-01-15 00:50:52 +00001089 def help_whatis(self):
Georg Brandl19564802006-05-10 17:13:20 +00001090 print >>self.stdout, """whatis arg
Tim Peters2344fae2001-01-15 00:50:52 +00001091Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001092
Tim Peters2344fae2001-01-15 00:50:52 +00001093 def help_EOF(self):
Georg Brandl19564802006-05-10 17:13:20 +00001094 print >>self.stdout, """EOF
Tim Peters2344fae2001-01-15 00:50:52 +00001095Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001096
Tim Peters2344fae2001-01-15 00:50:52 +00001097 def help_alias(self):
Georg Brandl19564802006-05-10 17:13:20 +00001098 print >>self.stdout, """alias [name [command [parameter parameter ...] ]]
Tim Peters2344fae2001-01-15 00:50:52 +00001099Creates an alias called 'name' the executes 'command'. The command
1100must *not* be enclosed in quotes. Replaceable parameters are
1101indicated by %1, %2, and so on, while %* is replaced by all the
1102parameters. If no command is given, the current alias for name
1103is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +00001104
Tim Peters2344fae2001-01-15 00:50:52 +00001105Aliases may be nested and can contain anything that can be
1106legally typed at the pdb prompt. Note! You *can* override
1107internal pdb commands with aliases! Those internal commands
1108are then hidden until the alias is removed. Aliasing is recursively
1109applied to the first word of the command line; all other words
1110in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +00001111
Tim Peters2344fae2001-01-15 00:50:52 +00001112Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +00001113
Tim Peters2344fae2001-01-15 00:50:52 +00001114#Print instance variables (usage "pi classInst")
1115alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +00001116
Tim Peters2344fae2001-01-15 00:50:52 +00001117#Print instance variables in self
1118alias ps pi self
1119"""
Guido van Rossum2424f851998-09-11 22:50:09 +00001120
Tim Peters2344fae2001-01-15 00:50:52 +00001121 def help_unalias(self):
Georg Brandl19564802006-05-10 17:13:20 +00001122 print >>self.stdout, """unalias name
Tim Peters2344fae2001-01-15 00:50:52 +00001123Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001124
Martin v. Löwisbd30f522006-04-17 17:08:37 +00001125 def help_commands(self):
Georg Brandl19564802006-05-10 17:13:20 +00001126 print >>self.stdout, """commands [bpnumber]
Martin v. Löwisbd30f522006-04-17 17:08:37 +00001127(com) ...
1128(com) end
1129(Pdb)
1130
1131Specify a list of commands for breakpoint number bpnumber. The
1132commands themselves appear on the following lines. Type a line
1133containing just 'end' to terminate the commands.
1134
1135To remove all commands from a breakpoint, type commands and
1136follow it immediately with end; that is, give no commands.
1137
1138With no bpnumber argument, commands refers to the last
1139breakpoint set.
1140
1141You can use breakpoint commands to start your program up again.
1142Simply use the continue command, or step, or any other
1143command that resumes execution.
1144
1145Specifying any command resuming execution (currently continue,
1146step, next, return, jump, quit and their abbreviations) terminates
1147the command list (as if that command was immediately followed by end).
1148This is because any time you resume execution
Martin v. Löwisf62eee12006-04-17 17:37:09 +00001149(even with a simple next or step), you may encounter
Martin v. Löwisbd30f522006-04-17 17:08:37 +00001150another breakpoint--which could have its own command list, leading to
1151ambiguities about which list to execute.
1152
1153 If you use the 'silent' command in the command list, the
1154usual message about stopping at a breakpoint is not printed. This may
1155be desirable for breakpoints that are to print a specific message and
1156then continue. If none of the other commands print anything, you
1157see no sign that the breakpoint was reached.
1158"""
1159
Tim Peters2344fae2001-01-15 00:50:52 +00001160 def help_pdb(self):
1161 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001162
Tim Peters2344fae2001-01-15 00:50:52 +00001163 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001164 """Helper function for break/clear parsing -- may be overridden.
1165
1166 lookupmodule() translates (possibly incomplete) file or module name
1167 into an absolute file name.
1168 """
1169 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001170 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001171 f = os.path.join(sys.path[0], filename)
1172 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1173 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001174 root, ext = os.path.splitext(filename)
1175 if ext == '':
1176 filename = filename + '.py'
1177 if os.path.isabs(filename):
1178 return filename
1179 for dirname in sys.path:
1180 while os.path.islink(dirname):
1181 dirname = os.readlink(dirname)
1182 fullname = os.path.join(dirname, filename)
1183 if os.path.exists(fullname):
1184 return fullname
1185 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001186
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001187 def _runscript(self, filename):
Georg Brandlb6ae6aa2007-03-13 21:58:44 +00001188 # The script has to run in __main__ namespace (or imports from
1189 # __main__ will break).
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001190 #
Georg Brandlb6ae6aa2007-03-13 21:58:44 +00001191 # So we clear up the __main__ and set several special variables
1192 # (this gets rid of pdb's globals and cleans old variables on restarts).
1193 import __main__
1194 __main__.__dict__.clear()
1195 __main__.__dict__.update({"__name__" : "__main__",
1196 "__file__" : filename,
1197 "__builtins__": __builtins__,
1198 })
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001199
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001200 # When bdb sets tracing, a number of call and line events happens
1201 # BEFORE debugger even reaches user's code (and the exact sequence of
1202 # events depends on python version). So we take special measures to
1203 # avoid stopping before we reach the main script (see user_line and
1204 # user_call for details).
1205 self._wait_for_mainpyfile = 1
1206 self.mainpyfile = self.canonic(filename)
1207 self._user_requested_quit = 0
1208 statement = 'execfile( "%s")' % filename
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001209 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001210
Guido van Rossum35771131992-09-08 11:59:04 +00001211# Simplified interface
1212
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001213def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001214 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001215
1216def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001217 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001218
1219def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001220 # B/W compatibility
1221 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001222
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001223def runcall(*args, **kwds):
1224 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001225
Guido van Rossumb6775db1994-08-01 11:34:53 +00001226def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001227 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001228
1229# Post-Mortem interface
1230
Facundo Batistac54aec12008-03-08 16:50:27 +00001231def post_mortem(t=None):
1232 # handling the default
1233 if t is None:
1234 # sys.exc_info() returns (type, value, traceback) if an exception is
1235 # being handled, otherwise it returns None
1236 t = sys.exc_info()[2]
1237 if t is None:
1238 raise ValueError("A valid traceback must be passed if no "
1239 "exception is being handled")
1240
Tim Peters2344fae2001-01-15 00:50:52 +00001241 p = Pdb()
1242 p.reset()
Benjamin Petersonc18574c2008-10-22 21:16:34 +00001243 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001244
1245def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001246 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001247
1248
1249# Main program for testing
1250
Guido van Rossum23efba41992-01-27 16:58:47 +00001251TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001252
Guido van Rossum921c8241992-01-10 14:54:42 +00001253def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001254 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001255
1256# print help
1257def help():
Tim Peters2344fae2001-01-15 00:50:52 +00001258 for dirname in sys.path:
1259 fullname = os.path.join(dirname, 'pdb.doc')
1260 if os.path.exists(fullname):
1261 sts = os.system('${PAGER-more} '+fullname)
1262 if sts: print '*** Pager exit status:', sts
1263 break
1264 else:
1265 print 'Sorry, can\'t find the help file "pdb.doc"',
1266 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +00001267
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001268def main():
Benjamin Peterson13be2cf2008-03-26 11:57:47 +00001269 if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
Tim Peters2344fae2001-01-15 00:50:52 +00001270 print "usage: pdb.py scriptfile [arg] ..."
1271 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001272
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001273 mainpyfile = sys.argv[1] # Get script filename
1274 if not os.path.exists(mainpyfile):
1275 print 'Error:', mainpyfile, 'does not exist'
Tim Peters2344fae2001-01-15 00:50:52 +00001276 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001277
Tim Peters2344fae2001-01-15 00:50:52 +00001278 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001279
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001280 # Replace pdb's dir with script's dir in front of module search path.
1281 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001282
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001283 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1284 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl8e84c652007-03-13 21:08:15 +00001285 # changed by the user from the command line. There is a "restart" command which
1286 # allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001287 pdb = Pdb()
1288 while 1:
1289 try:
1290 pdb._runscript(mainpyfile)
1291 if pdb._user_requested_quit:
1292 break
Tim Peterse718f612004-10-12 21:51:32 +00001293 print "The program finished and will be restarted"
Georg Brandl8e84c652007-03-13 21:08:15 +00001294 except Restart:
1295 print "Restarting", mainpyfile, "with arguments:"
1296 print "\t" + " ".join(sys.argv[1:])
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001297 except SystemExit:
1298 # In most cases SystemExit does not warrant a post-mortem session.
1299 print "The program exited via sys.exit(). Exit status: ",
1300 print sys.exc_info()[1]
1301 except:
1302 traceback.print_exc()
1303 print "Uncaught exception. Entering post mortem debugging"
1304 print "Running 'cont' or 'step' will restart the program"
1305 t = sys.exc_info()[2]
Benjamin Petersonc18574c2008-10-22 21:16:34 +00001306 pdb.interaction(None, t)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001307 print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
1308
1309
1310# When invoked as main program, invoke the debugger on a script
Georg Brandlb6ae6aa2007-03-13 21:58:44 +00001311if __name__ == '__main__':
1312 import pdb
1313 pdb.main()