blob: eae62960ce92184a96074ec52c5320cf20aab6a6 [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 Brandl4d4313d2009-05-05 08:54:11 +000061 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None):
62 bdb.Bdb.__init__(self, skip=skip)
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):
Georg Brandl58152202009-05-05 09:06:02 +0000161 """Call every command that was set for the current active breakpoint
162 (if there is one).
163
164 Returns True if the normal interaction function must be called,
165 False otherwise."""
166 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
167 if getattr(self, "currentbp", False) and \
168 self.currentbp in self.commands:
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000169 currentbp = self.currentbp
170 self.currentbp = 0
171 lastcmd_back = self.lastcmd
172 self.setup(frame, None)
173 for line in self.commands[currentbp]:
174 self.onecmd(line)
175 self.lastcmd = lastcmd_back
176 if not self.commands_silent[currentbp]:
177 self.print_stack_entry(self.stack[self.curindex])
178 if self.commands_doprompt[currentbp]:
179 self.cmdloop()
180 self.forget()
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000181 return
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000182 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000183
Tim Peters2344fae2001-01-15 00:50:52 +0000184 def user_return(self, frame, return_value):
185 """This function is called when a return trap is set here."""
186 frame.f_locals['__return__'] = return_value
Georg Brandl19564802006-05-10 17:13:20 +0000187 print >>self.stdout, '--Return--'
Tim Peters2344fae2001-01-15 00:50:52 +0000188 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000189
Brett Cannonc6a30ec2008-08-01 01:36:47 +0000190 def user_exception(self, frame, exc_info):
191 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000192 """This function is called if an exception occurs,
193 but only if we are to stop at or just below this level."""
194 frame.f_locals['__exception__'] = exc_type, exc_value
195 if type(exc_type) == type(''):
196 exc_type_name = exc_type
197 else: exc_type_name = exc_type.__name__
Georg Brandl19564802006-05-10 17:13:20 +0000198 print >>self.stdout, exc_type_name + ':', _saferepr(exc_value)
Tim Peters2344fae2001-01-15 00:50:52 +0000199 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000200
Tim Peters2344fae2001-01-15 00:50:52 +0000201 # General interaction function
202
203 def interaction(self, frame, traceback):
204 self.setup(frame, traceback)
205 self.print_stack_entry(self.stack[self.curindex])
206 self.cmdloop()
207 self.forget()
208
Georg Brandl58b8b952009-04-01 21:54:21 +0000209 def displayhook(self, obj):
210 """Custom displayhook for the exec in default(), which prevents
211 assignment of the _ variable in the builtins.
212 """
Georg Brandldd98e042009-04-02 17:43:07 +0000213 print repr(obj)
Georg Brandl58b8b952009-04-01 21:54:21 +0000214
Tim Peters2344fae2001-01-15 00:50:52 +0000215 def default(self, line):
216 if line[:1] == '!': line = line[1:]
Georg Brandle361bcb2009-04-01 23:32:17 +0000217 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000218 globals = self.curframe.f_globals
219 try:
220 code = compile(line + '\n', '<stdin>', 'single')
Amaury Forgeot d'Arcff0f2672008-01-15 21:25:11 +0000221 save_stdout = sys.stdout
222 save_stdin = sys.stdin
Georg Brandl58b8b952009-04-01 21:54:21 +0000223 save_displayhook = sys.displayhook
Guido van Rossumcad37242008-01-15 17:59:29 +0000224 try:
225 sys.stdin = self.stdin
226 sys.stdout = self.stdout
Georg Brandl58b8b952009-04-01 21:54:21 +0000227 sys.displayhook = self.displayhook
Guido van Rossumcad37242008-01-15 17:59:29 +0000228 exec code in globals, locals
229 finally:
230 sys.stdout = save_stdout
231 sys.stdin = save_stdin
Georg Brandl58b8b952009-04-01 21:54:21 +0000232 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000233 except:
234 t, v = sys.exc_info()[:2]
235 if type(t) == type(''):
236 exc_type_name = t
237 else: exc_type_name = t.__name__
Georg Brandl19564802006-05-10 17:13:20 +0000238 print >>self.stdout, '***', exc_type_name + ':', v
Tim Peters2344fae2001-01-15 00:50:52 +0000239
240 def precmd(self, line):
241 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000242 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000243 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000244 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000245 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000246 line = self.aliases[args[0]]
247 ii = 1
248 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000249 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000250 tmpArg)
251 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000252 line = line.replace("%*", ' '.join(args[1:]))
253 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000254 # split into ';;' separated commands
255 # unless it's an alias command
256 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000257 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000258 if marker >= 0:
259 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000260 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000261 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000262 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000263 return line
264
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000265 def onecmd(self, line):
266 """Interpret the argument as though it had been typed in response
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000267 to the prompt.
268
Andrew M. Kuchling9aed98f2006-07-27 12:18:20 +0000269 Checks whether this line is typed at the normal prompt or in
Tim Petersdaea0352006-07-27 15:11:00 +0000270 a breakpoint command list definition.
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000271 """
272 if not self.commands_defining:
273 return cmd.Cmd.onecmd(self, line)
274 else:
275 return self.handle_command_def(line)
276
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000277 def handle_command_def(self,line):
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000278 """ Handles one command line during command list definition. """
279 cmd, arg, line = self.parseline(line)
280 if cmd == 'silent':
281 self.commands_silent[self.commands_bnum] = True
282 return # continue to handle other cmd def in the cmd list
283 elif cmd == 'end':
284 self.cmdqueue = []
285 return 1 # end of cmd list
286 cmdlist = self.commands[self.commands_bnum]
287 if (arg):
288 cmdlist.append(cmd+' '+arg)
289 else:
290 cmdlist.append(cmd)
291 # Determine if we must stop
292 try:
293 func = getattr(self, 'do_' + cmd)
294 except AttributeError:
295 func = self.default
Georg Brandl58152202009-05-05 09:06:02 +0000296 # one of the resuming commands
297 if func.func_name in self.commands_resuming:
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000298 self.commands_doprompt[self.commands_bnum] = False
299 self.cmdqueue = []
300 return 1
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000301 return
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000302
Tim Peters2344fae2001-01-15 00:50:52 +0000303 # Command definitions, called by cmdloop()
304 # The argument is the remaining string on the command line
305 # Return true to exit from the command loop
306
307 do_h = cmd.Cmd.do_help
308
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000309 def do_commands(self, arg):
Georg Brandl58152202009-05-05 09:06:02 +0000310 """Defines a list of commands associated to a breakpoint.
311
312 Those commands will be executed whenever the breakpoint causes
313 the program to stop execution."""
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000314 if not arg:
315 bnum = len(bdb.Breakpoint.bpbynumber)-1
316 else:
317 try:
318 bnum = int(arg)
319 except:
Georg Brandl58152202009-05-05 09:06:02 +0000320 print >>self.stdout, "Usage : commands [bnum]\n ..." \
321 "\n end"
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000322 return
323 self.commands_bnum = bnum
324 self.commands[bnum] = []
325 self.commands_doprompt[bnum] = True
326 self.commands_silent[bnum] = False
327 prompt_back = self.prompt
328 self.prompt = '(com) '
329 self.commands_defining = True
330 self.cmdloop()
331 self.commands_defining = False
332 self.prompt = prompt_back
333
Tim Peters2344fae2001-01-15 00:50:52 +0000334 def do_break(self, arg, temporary = 0):
335 # break [ ([filename:]lineno | function) [, "condition"] ]
336 if not arg:
337 if self.breaks: # There's at least one
Georg Brandl19564802006-05-10 17:13:20 +0000338 print >>self.stdout, "Num Type Disp Enb Where"
Tim Peters2344fae2001-01-15 00:50:52 +0000339 for bp in bdb.Breakpoint.bpbynumber:
340 if bp:
Georg Brandl19564802006-05-10 17:13:20 +0000341 bp.bpprint(self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000342 return
343 # parse arguments; comma has lowest precedence
344 # and cannot occur in filename
345 filename = None
346 lineno = None
347 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000348 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000349 if comma > 0:
350 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000351 cond = arg[comma+1:].lstrip()
352 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000353 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000354 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000355 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000356 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000357 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000358 f = self.lookupmodule(filename)
359 if not f:
Georg Brandl19564802006-05-10 17:13:20 +0000360 print >>self.stdout, '*** ', repr(filename),
361 print >>self.stdout, 'not found from sys.path'
Tim Peters2344fae2001-01-15 00:50:52 +0000362 return
363 else:
364 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000365 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000366 try:
367 lineno = int(arg)
368 except ValueError, msg:
Georg Brandl19564802006-05-10 17:13:20 +0000369 print >>self.stdout, '*** Bad lineno:', arg
Tim Peters2344fae2001-01-15 00:50:52 +0000370 return
371 else:
372 # no colon; can be lineno or function
373 try:
374 lineno = int(arg)
375 except ValueError:
376 try:
377 func = eval(arg,
378 self.curframe.f_globals,
Georg Brandle361bcb2009-04-01 23:32:17 +0000379 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000380 except:
381 func = arg
382 try:
383 if hasattr(func, 'im_func'):
384 func = func.im_func
385 code = func.func_code
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000386 #use co_name to identify the bkpt (function names
387 #could be aliased, but co_name is invariant)
388 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000389 lineno = code.co_firstlineno
390 filename = code.co_filename
391 except:
392 # last thing to try
393 (ok, filename, ln) = self.lineinfo(arg)
394 if not ok:
Georg Brandl19564802006-05-10 17:13:20 +0000395 print >>self.stdout, '*** The specified object',
396 print >>self.stdout, repr(arg),
397 print >>self.stdout, 'is not a function'
398 print >>self.stdout, 'or was not found along sys.path.'
Tim Peters2344fae2001-01-15 00:50:52 +0000399 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000400 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000401 lineno = int(ln)
402 if not filename:
403 filename = self.defaultFile()
404 # Check for reasonable breakpoint
405 line = self.checkline(filename, lineno)
406 if line:
407 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000408 err = self.set_break(filename, line, temporary, cond, funcname)
Georg Brandl19564802006-05-10 17:13:20 +0000409 if err: print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000410 else:
411 bp = self.get_breaks(filename, line)[-1]
Georg Brandl19564802006-05-10 17:13:20 +0000412 print >>self.stdout, "Breakpoint %d at %s:%d" % (bp.number,
413 bp.file,
414 bp.line)
Tim Peters2344fae2001-01-15 00:50:52 +0000415
416 # To be overridden in derived debuggers
417 def defaultFile(self):
418 """Produce a reasonable default."""
419 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000420 if filename == '<string>' and self.mainpyfile:
421 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000422 return filename
423
424 do_b = do_break
425
426 def do_tbreak(self, arg):
427 self.do_break(arg, 1)
428
429 def lineinfo(self, identifier):
430 failed = (None, None, None)
431 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000432 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000433 if len(idstring) == 1:
434 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000435 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000436 elif len(idstring) == 3:
437 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000438 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000439 else:
440 return failed
441 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000442 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000443 # Protection for derived debuggers
444 if parts[0] == 'self':
445 del parts[0]
446 if len(parts) == 0:
447 return failed
448 # Best first guess at file to look at
449 fname = self.defaultFile()
450 if len(parts) == 1:
451 item = parts[0]
452 else:
453 # More than one part.
454 # First is module, second is method/class
455 f = self.lookupmodule(parts[0])
456 if f:
457 fname = f
458 item = parts[1]
459 answer = find_function(item, fname)
460 return answer or failed
461
462 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000463 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000464
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000465 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
466 line or EOF). Warning: testing is not comprehensive.
467 """
Nick Coghlana2053472008-12-14 10:54:50 +0000468 line = linecache.getline(filename, lineno, self.curframe.f_globals)
Tim Peters2344fae2001-01-15 00:50:52 +0000469 if not line:
Georg Brandl19564802006-05-10 17:13:20 +0000470 print >>self.stdout, 'End of file'
Tim Peters2344fae2001-01-15 00:50:52 +0000471 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000472 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000473 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000474 if (not line or (line[0] == '#') or
475 (line[:3] == '"""') or line[:3] == "'''"):
Georg Brandl19564802006-05-10 17:13:20 +0000476 print >>self.stdout, '*** Blank or comment'
Tim Peters2344fae2001-01-15 00:50:52 +0000477 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000478 return lineno
479
480 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000481 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000482 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000483 try:
484 i = int(i)
485 except ValueError:
Georg Brandl19564802006-05-10 17:13:20 +0000486 print >>self.stdout, 'Breakpoint index %r is not a number' % i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000487 continue
488
489 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Georg Brandl19564802006-05-10 17:13:20 +0000490 print >>self.stdout, 'No breakpoint numbered', i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000491 continue
492
493 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000494 if bp:
495 bp.enable()
496
497 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000498 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000499 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000500 try:
501 i = int(i)
502 except ValueError:
Georg Brandl19564802006-05-10 17:13:20 +0000503 print >>self.stdout, 'Breakpoint index %r is not a number' % i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000504 continue
Tim Petersf545baa2003-06-15 23:26:30 +0000505
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000506 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Georg Brandl19564802006-05-10 17:13:20 +0000507 print >>self.stdout, 'No breakpoint numbered', i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000508 continue
509
510 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000511 if bp:
512 bp.disable()
513
514 def do_condition(self, arg):
515 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000516 args = arg.split(' ', 1)
Georg Brandle4980832007-01-22 21:23:41 +0000517 try:
518 bpnum = int(args[0].strip())
519 except ValueError:
520 # something went wrong
521 print >>self.stdout, \
522 'Breakpoint index %r is not a number' % args[0]
Georg Brandlb2783182007-03-11 08:28:46 +0000523 return
Tim Peters2344fae2001-01-15 00:50:52 +0000524 try:
525 cond = args[1]
526 except:
527 cond = None
Collin Winter2faa9e12007-03-11 16:00:20 +0000528 try:
529 bp = bdb.Breakpoint.bpbynumber[bpnum]
530 except IndexError:
531 print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
532 return
Tim Peters2344fae2001-01-15 00:50:52 +0000533 if bp:
534 bp.cond = cond
535 if not cond:
Georg Brandl19564802006-05-10 17:13:20 +0000536 print >>self.stdout, 'Breakpoint', bpnum,
537 print >>self.stdout, 'is now unconditional.'
Tim Peters2344fae2001-01-15 00:50:52 +0000538
539 def do_ignore(self,arg):
540 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000541 args = arg.split()
Georg Brandle4980832007-01-22 21:23:41 +0000542 try:
543 bpnum = int(args[0].strip())
544 except ValueError:
545 # something went wrong
546 print >>self.stdout, \
547 'Breakpoint index %r is not a number' % args[0]
Georg Brandlb2783182007-03-11 08:28:46 +0000548 return
Tim Peters2344fae2001-01-15 00:50:52 +0000549 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000550 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000551 except:
552 count = 0
Collin Winter2faa9e12007-03-11 16:00:20 +0000553 try:
554 bp = bdb.Breakpoint.bpbynumber[bpnum]
555 except IndexError:
556 print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
557 return
Tim Peters2344fae2001-01-15 00:50:52 +0000558 if bp:
559 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000560 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000561 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000562 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000563 reply = reply + '%d crossings' % count
564 else:
565 reply = reply + '1 crossing'
Georg Brandl19564802006-05-10 17:13:20 +0000566 print >>self.stdout, reply + ' of breakpoint %d.' % bpnum
Tim Peters2344fae2001-01-15 00:50:52 +0000567 else:
Georg Brandl19564802006-05-10 17:13:20 +0000568 print >>self.stdout, 'Will stop next time breakpoint',
569 print >>self.stdout, bpnum, 'is reached.'
Tim Peters2344fae2001-01-15 00:50:52 +0000570
571 def do_clear(self, arg):
572 """Three possibilities, tried in this order:
573 clear -> clear all breaks, ask for confirmation
574 clear file:lineno -> clear all breaks at file:lineno
575 clear bpno bpno ... -> clear breakpoints by number"""
576 if not arg:
577 try:
578 reply = raw_input('Clear all breaks? ')
579 except EOFError:
580 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000581 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000582 if reply in ('y', 'yes'):
583 self.clear_all_breaks()
584 return
585 if ':' in arg:
586 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000587 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000588 filename = arg[:i]
589 arg = arg[i+1:]
590 try:
591 lineno = int(arg)
Georg Brandl23d9d452006-05-03 18:12:33 +0000592 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000593 err = "Invalid line number (%s)" % arg
594 else:
595 err = self.clear_break(filename, lineno)
Georg Brandl19564802006-05-10 17:13:20 +0000596 if err: print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000597 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000598 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000599 for i in numberlist:
Georg Brandl23d9d452006-05-03 18:12:33 +0000600 try:
601 i = int(i)
602 except ValueError:
Georg Brandl19564802006-05-10 17:13:20 +0000603 print >>self.stdout, 'Breakpoint index %r is not a number' % i
Georg Brandl23d9d452006-05-03 18:12:33 +0000604 continue
605
Georg Brandl6d2b3462005-08-24 07:36:17 +0000606 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Georg Brandl19564802006-05-10 17:13:20 +0000607 print >>self.stdout, 'No breakpoint numbered', i
Georg Brandl6d2b3462005-08-24 07:36:17 +0000608 continue
Tim Peters2344fae2001-01-15 00:50:52 +0000609 err = self.clear_bpbynumber(i)
610 if err:
Georg Brandl19564802006-05-10 17:13:20 +0000611 print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000612 else:
Georg Brandl19564802006-05-10 17:13:20 +0000613 print >>self.stdout, 'Deleted breakpoint', i
Tim Peters2344fae2001-01-15 00:50:52 +0000614 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
615
616 def do_where(self, arg):
617 self.print_stack_trace()
618 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000619 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000620
621 def do_up(self, arg):
622 if self.curindex == 0:
Georg Brandl19564802006-05-10 17:13:20 +0000623 print >>self.stdout, '*** Oldest frame'
Tim Peters2344fae2001-01-15 00:50:52 +0000624 else:
625 self.curindex = self.curindex - 1
626 self.curframe = self.stack[self.curindex][0]
Georg Brandl569fc962009-04-02 02:00:01 +0000627 self.curframe_locals = self.curframe.f_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000628 self.print_stack_entry(self.stack[self.curindex])
629 self.lineno = None
630 do_u = do_up
631
632 def do_down(self, arg):
633 if self.curindex + 1 == len(self.stack):
Georg Brandl19564802006-05-10 17:13:20 +0000634 print >>self.stdout, '*** Newest frame'
Tim Peters2344fae2001-01-15 00:50:52 +0000635 else:
636 self.curindex = self.curindex + 1
637 self.curframe = self.stack[self.curindex][0]
Georg Brandl569fc962009-04-02 02:00:01 +0000638 self.curframe_locals = self.curframe.f_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000639 self.print_stack_entry(self.stack[self.curindex])
640 self.lineno = None
641 do_d = do_down
642
Benjamin Peterson98353942008-05-11 14:13:25 +0000643 def do_until(self, arg):
644 self.set_until(self.curframe)
645 return 1
646 do_unt = do_until
647
Tim Peters2344fae2001-01-15 00:50:52 +0000648 def do_step(self, arg):
649 self.set_step()
650 return 1
651 do_s = do_step
652
653 def do_next(self, arg):
654 self.set_next(self.curframe)
655 return 1
656 do_n = do_next
657
Georg Brandl8e84c652007-03-13 21:08:15 +0000658 def do_run(self, arg):
Georg Brandl58152202009-05-05 09:06:02 +0000659 """Restart program by raising an exception to be caught in the main
660 debugger loop. If arguments were given, set them in sys.argv."""
Georg Brandl8e84c652007-03-13 21:08:15 +0000661 if arg:
662 import shlex
663 argv0 = sys.argv[0:1]
664 sys.argv = shlex.split(arg)
665 sys.argv[:0] = argv0
666 raise Restart
667
668 do_restart = do_run
669
Tim Peters2344fae2001-01-15 00:50:52 +0000670 def do_return(self, arg):
671 self.set_return(self.curframe)
672 return 1
673 do_r = do_return
674
675 def do_continue(self, arg):
676 self.set_continue()
677 return 1
678 do_c = do_cont = do_continue
679
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000680 def do_jump(self, arg):
681 if self.curindex + 1 != len(self.stack):
Georg Brandl19564802006-05-10 17:13:20 +0000682 print >>self.stdout, "*** You can only jump within the bottom frame"
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000683 return
684 try:
685 arg = int(arg)
686 except ValueError:
Georg Brandl19564802006-05-10 17:13:20 +0000687 print >>self.stdout, "*** The 'jump' command requires a line number."
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000688 else:
689 try:
690 # Do the jump, fix up our copy of the stack, and display the
691 # new position
692 self.curframe.f_lineno = arg
693 self.stack[self.curindex] = self.stack[self.curindex][0], arg
694 self.print_stack_entry(self.stack[self.curindex])
695 except ValueError, e:
Georg Brandl19564802006-05-10 17:13:20 +0000696 print >>self.stdout, '*** Jump failed:', e
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000697 do_j = do_jump
698
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000699 def do_debug(self, arg):
700 sys.settrace(None)
701 globals = self.curframe.f_globals
Georg Brandle361bcb2009-04-01 23:32:17 +0000702 locals = self.curframe_locals
Guido van Rossumcad37242008-01-15 17:59:29 +0000703 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +0000704 p.prompt = "(%s) " % self.prompt.strip()
Georg Brandl19564802006-05-10 17:13:20 +0000705 print >>self.stdout, "ENTERING RECURSIVE DEBUGGER"
Guido van Rossumed538d82003-04-09 19:36:34 +0000706 sys.call_tracing(p.run, (arg, globals, locals))
Georg Brandl19564802006-05-10 17:13:20 +0000707 print >>self.stdout, "LEAVING RECURSIVE DEBUGGER"
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000708 sys.settrace(self.trace_dispatch)
709 self.lastcmd = p.lastcmd
710
Tim Peters2344fae2001-01-15 00:50:52 +0000711 def do_quit(self, arg):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000712 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000713 self.set_quit()
714 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000715
Tim Peters2344fae2001-01-15 00:50:52 +0000716 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000717 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000718
Guido van Rossumeef26072003-01-13 21:13:55 +0000719 def do_EOF(self, arg):
Georg Brandl19564802006-05-10 17:13:20 +0000720 print >>self.stdout
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000721 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000722 self.set_quit()
723 return 1
724
Tim Peters2344fae2001-01-15 00:50:52 +0000725 def do_args(self, arg):
Georg Brandle361bcb2009-04-01 23:32:17 +0000726 co = self.curframe.f_code
727 dict = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000728 n = co.co_argcount
729 if co.co_flags & 4: n = n+1
730 if co.co_flags & 8: n = n+1
731 for i in range(n):
732 name = co.co_varnames[i]
Georg Brandl19564802006-05-10 17:13:20 +0000733 print >>self.stdout, name, '=',
734 if name in dict: print >>self.stdout, dict[name]
735 else: print >>self.stdout, "*** undefined ***"
Tim Peters2344fae2001-01-15 00:50:52 +0000736 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000737
Tim Peters2344fae2001-01-15 00:50:52 +0000738 def do_retval(self, arg):
Georg Brandle361bcb2009-04-01 23:32:17 +0000739 if '__return__' in self.curframe_locals:
740 print >>self.stdout, self.curframe_locals['__return__']
Tim Peters2344fae2001-01-15 00:50:52 +0000741 else:
Georg Brandl19564802006-05-10 17:13:20 +0000742 print >>self.stdout, '*** Not yet returned!'
Tim Peters2344fae2001-01-15 00:50:52 +0000743 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000744
Barry Warsaw210bd202002-11-05 22:40:20 +0000745 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000746 try:
Barry Warsaw210bd202002-11-05 22:40:20 +0000747 return eval(arg, self.curframe.f_globals,
Georg Brandle361bcb2009-04-01 23:32:17 +0000748 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000749 except:
750 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000751 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000752 exc_type_name = t
753 else: exc_type_name = t.__name__
Georg Brandl19564802006-05-10 17:13:20 +0000754 print >>self.stdout, '***', exc_type_name + ':', repr(v)
Barry Warsaw210bd202002-11-05 22:40:20 +0000755 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000756
Barry Warsaw210bd202002-11-05 22:40:20 +0000757 def do_p(self, arg):
758 try:
Georg Brandl19564802006-05-10 17:13:20 +0000759 print >>self.stdout, repr(self._getval(arg))
Barry Warsaw210bd202002-11-05 22:40:20 +0000760 except:
761 pass
762
763 def do_pp(self, arg):
764 try:
Georg Brandl19564802006-05-10 17:13:20 +0000765 pprint.pprint(self._getval(arg), self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +0000766 except:
767 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000768
Tim Peters2344fae2001-01-15 00:50:52 +0000769 def do_list(self, arg):
770 self.lastcmd = 'list'
771 last = None
772 if arg:
773 try:
774 x = eval(arg, {}, {})
775 if type(x) == type(()):
776 first, last = x
777 first = int(first)
778 last = int(last)
779 if last < first:
780 # Assume it's a count
781 last = first + last
782 else:
783 first = max(1, int(x) - 5)
784 except:
Georg Brandl19564802006-05-10 17:13:20 +0000785 print >>self.stdout, '*** Error in argument:', repr(arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000786 return
787 elif self.lineno is None:
788 first = max(1, self.curframe.f_lineno - 5)
789 else:
790 first = self.lineno + 1
791 if last is None:
792 last = first + 10
793 filename = self.curframe.f_code.co_filename
794 breaklist = self.get_file_breaks(filename)
795 try:
796 for lineno in range(first, last+1):
Georg Brandl58152202009-05-05 09:06:02 +0000797 line = linecache.getline(filename, lineno,
798 self.curframe.f_globals)
Tim Peters2344fae2001-01-15 00:50:52 +0000799 if not line:
Georg Brandl19564802006-05-10 17:13:20 +0000800 print >>self.stdout, '[EOF]'
Tim Peters2344fae2001-01-15 00:50:52 +0000801 break
802 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000803 s = repr(lineno).rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000804 if len(s) < 4: s = s + ' '
805 if lineno in breaklist: s = s + 'B'
806 else: s = s + ' '
807 if lineno == self.curframe.f_lineno:
808 s = s + '->'
Georg Brandl19564802006-05-10 17:13:20 +0000809 print >>self.stdout, s + '\t' + line,
Tim Peters2344fae2001-01-15 00:50:52 +0000810 self.lineno = lineno
811 except KeyboardInterrupt:
812 pass
813 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000814
Tim Peters2344fae2001-01-15 00:50:52 +0000815 def do_whatis(self, arg):
816 try:
817 value = eval(arg, self.curframe.f_globals,
Georg Brandle361bcb2009-04-01 23:32:17 +0000818 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000819 except:
820 t, v = sys.exc_info()[:2]
821 if type(t) == type(''):
822 exc_type_name = t
823 else: exc_type_name = t.__name__
Georg Brandl19564802006-05-10 17:13:20 +0000824 print >>self.stdout, '***', exc_type_name + ':', repr(v)
Tim Peters2344fae2001-01-15 00:50:52 +0000825 return
826 code = None
827 # Is it a function?
828 try: code = value.func_code
829 except: pass
830 if code:
Georg Brandl19564802006-05-10 17:13:20 +0000831 print >>self.stdout, 'Function', code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000832 return
833 # Is it an instance method?
834 try: code = value.im_func.func_code
835 except: pass
836 if code:
Georg Brandl19564802006-05-10 17:13:20 +0000837 print >>self.stdout, 'Method', code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000838 return
839 # None of the above...
Georg Brandl19564802006-05-10 17:13:20 +0000840 print >>self.stdout, type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000841
Tim Peters2344fae2001-01-15 00:50:52 +0000842 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000843 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000844 if len(args) == 0:
845 keys = self.aliases.keys()
846 keys.sort()
847 for alias in keys:
Georg Brandl19564802006-05-10 17:13:20 +0000848 print >>self.stdout, "%s = %s" % (alias, self.aliases[alias])
Tim Peters2344fae2001-01-15 00:50:52 +0000849 return
Guido van Rossum08454592002-07-12 13:10:53 +0000850 if args[0] in self.aliases and len(args) == 1:
Georg Brandl19564802006-05-10 17:13:20 +0000851 print >>self.stdout, "%s = %s" % (args[0], self.aliases[args[0]])
Tim Peters2344fae2001-01-15 00:50:52 +0000852 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000853 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000854
Tim Peters2344fae2001-01-15 00:50:52 +0000855 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000856 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000857 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000858 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000859 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000860
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000861 #list of all the commands making the program resume execution.
Georg Brandl19564802006-05-10 17:13:20 +0000862 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
863 'do_quit', 'do_jump']
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000864
Tim Peters2344fae2001-01-15 00:50:52 +0000865 # Print a traceback starting at the top stack frame.
866 # The most recently entered frame is printed last;
867 # this is different from dbx and gdb, but consistent with
868 # the Python interpreter's stack trace.
869 # It is also consistent with the up/down commands (which are
870 # compatible with dbx and gdb: up moves towards 'main()'
871 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000872
Tim Peters2344fae2001-01-15 00:50:52 +0000873 def print_stack_trace(self):
874 try:
875 for frame_lineno in self.stack:
876 self.print_stack_entry(frame_lineno)
877 except KeyboardInterrupt:
878 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000879
Tim Peters2344fae2001-01-15 00:50:52 +0000880 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
881 frame, lineno = frame_lineno
882 if frame is self.curframe:
Georg Brandl19564802006-05-10 17:13:20 +0000883 print >>self.stdout, '>',
Tim Peters2344fae2001-01-15 00:50:52 +0000884 else:
Georg Brandl19564802006-05-10 17:13:20 +0000885 print >>self.stdout, ' ',
886 print >>self.stdout, self.format_stack_entry(frame_lineno,
887 prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000888
Guido van Rossum921c8241992-01-10 14:54:42 +0000889
Tim Peters2344fae2001-01-15 00:50:52 +0000890 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000891
Tim Peters2344fae2001-01-15 00:50:52 +0000892 def help_help(self):
893 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000894
Tim Peters2344fae2001-01-15 00:50:52 +0000895 def help_h(self):
Georg Brandl19564802006-05-10 17:13:20 +0000896 print >>self.stdout, """h(elp)
Tim Peters2344fae2001-01-15 00:50:52 +0000897Without argument, print the list of available commands.
898With a command name as argument, print help about that command
899"help pdb" pipes the full documentation file to the $PAGER
900"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000901
Tim Peters2344fae2001-01-15 00:50:52 +0000902 def help_where(self):
903 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000904
Tim Peters2344fae2001-01-15 00:50:52 +0000905 def help_w(self):
Georg Brandl19564802006-05-10 17:13:20 +0000906 print >>self.stdout, """w(here)
Tim Peters2344fae2001-01-15 00:50:52 +0000907Print a stack trace, with the most recent frame at the bottom.
908An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000909context of most commands. 'bt' is an alias for this command."""
910
911 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000912
Tim Peters2344fae2001-01-15 00:50:52 +0000913 def help_down(self):
914 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000915
Tim Peters2344fae2001-01-15 00:50:52 +0000916 def help_d(self):
Georg Brandl19564802006-05-10 17:13:20 +0000917 print >>self.stdout, """d(own)
Tim Peters2344fae2001-01-15 00:50:52 +0000918Move the current frame one level down in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000919(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000920
Tim Peters2344fae2001-01-15 00:50:52 +0000921 def help_up(self):
922 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000923
Tim Peters2344fae2001-01-15 00:50:52 +0000924 def help_u(self):
Georg Brandl19564802006-05-10 17:13:20 +0000925 print >>self.stdout, """u(p)
Tim Peters2344fae2001-01-15 00:50:52 +0000926Move the current frame one level up in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000927(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000928
Tim Peters2344fae2001-01-15 00:50:52 +0000929 def help_break(self):
930 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000931
Tim Peters2344fae2001-01-15 00:50:52 +0000932 def help_b(self):
Georg Brandl19564802006-05-10 17:13:20 +0000933 print >>self.stdout, """b(reak) ([file:]lineno | function) [, condition]
Tim Peters2344fae2001-01-15 00:50:52 +0000934With a line number argument, set a break there in the current
935file. With a function name, set a break at first executable line
936of that function. Without argument, list all breaks. If a second
937argument is present, it is a string specifying an expression
938which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000939
Tim Peters2344fae2001-01-15 00:50:52 +0000940The line number may be prefixed with a filename and a colon,
941to specify a breakpoint in another file (probably one that
942hasn't been loaded yet). The file is searched for on sys.path;
943the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000944
Tim Peters2344fae2001-01-15 00:50:52 +0000945 def help_clear(self):
946 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000947
Tim Peters2344fae2001-01-15 00:50:52 +0000948 def help_cl(self):
Georg Brandl19564802006-05-10 17:13:20 +0000949 print >>self.stdout, "cl(ear) filename:lineno"
950 print >>self.stdout, """cl(ear) [bpnumber [bpnumber...]]
Tim Peters2344fae2001-01-15 00:50:52 +0000951With a space separated list of breakpoint numbers, clear
952those breakpoints. Without argument, clear all breaks (but
953first ask confirmation). With a filename:lineno argument,
954clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000955
Tim Peters2344fae2001-01-15 00:50:52 +0000956Note that the argument is different from previous versions of
957the debugger (in python distributions 1.5.1 and before) where
958a linenumber was used instead of either filename:lineno or
959breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000960
Tim Peters2344fae2001-01-15 00:50:52 +0000961 def help_tbreak(self):
Georg Brandl58152202009-05-05 09:06:02 +0000962 print >>self.stdout, """tbreak same arguments as break, but breakpoint
963is removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000964
Tim Peters2344fae2001-01-15 00:50:52 +0000965 def help_enable(self):
Georg Brandl19564802006-05-10 17:13:20 +0000966 print >>self.stdout, """enable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +0000967Enables the breakpoints given as a space separated list of
968bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000969
Tim Peters2344fae2001-01-15 00:50:52 +0000970 def help_disable(self):
Georg Brandl19564802006-05-10 17:13:20 +0000971 print >>self.stdout, """disable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +0000972Disables the breakpoints given as a space separated list of
973bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000974
Tim Peters2344fae2001-01-15 00:50:52 +0000975 def help_ignore(self):
Georg Brandl19564802006-05-10 17:13:20 +0000976 print >>self.stdout, """ignore bpnumber count
Tim Peters2344fae2001-01-15 00:50:52 +0000977Sets the ignore count for the given breakpoint number. A breakpoint
978becomes active when the ignore count is zero. When non-zero, the
979count is decremented each time the breakpoint is reached and the
980breakpoint is not disabled and any associated condition evaluates
981to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000982
Tim Peters2344fae2001-01-15 00:50:52 +0000983 def help_condition(self):
Georg Brandl19564802006-05-10 17:13:20 +0000984 print >>self.stdout, """condition bpnumber str_condition
Tim Peters2344fae2001-01-15 00:50:52 +0000985str_condition is a string specifying an expression which
986must evaluate to true before the breakpoint is honored.
987If str_condition is absent, any existing condition is removed;
988i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +0000989
Tim Peters2344fae2001-01-15 00:50:52 +0000990 def help_step(self):
991 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000992
Tim Peters2344fae2001-01-15 00:50:52 +0000993 def help_s(self):
Georg Brandl19564802006-05-10 17:13:20 +0000994 print >>self.stdout, """s(tep)
Tim Peters2344fae2001-01-15 00:50:52 +0000995Execute the current line, stop at the first possible occasion
996(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000997
Benjamin Peterson98353942008-05-11 14:13:25 +0000998 def help_until(self):
999 self.help_unt()
1000
1001 def help_unt(self):
1002 print """unt(il)
1003Continue execution until the line with a number greater than the current
1004one is reached or until the current frame returns"""
1005
Tim Peters2344fae2001-01-15 00:50:52 +00001006 def help_next(self):
1007 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001008
Tim Peters2344fae2001-01-15 00:50:52 +00001009 def help_n(self):
Georg Brandl19564802006-05-10 17:13:20 +00001010 print >>self.stdout, """n(ext)
Tim Peters2344fae2001-01-15 00:50:52 +00001011Continue execution until the next line in the current function
1012is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001013
Tim Peters2344fae2001-01-15 00:50:52 +00001014 def help_return(self):
1015 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001016
Tim Peters2344fae2001-01-15 00:50:52 +00001017 def help_r(self):
Georg Brandl19564802006-05-10 17:13:20 +00001018 print >>self.stdout, """r(eturn)
Tim Peters2344fae2001-01-15 00:50:52 +00001019Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001020
Tim Peters2344fae2001-01-15 00:50:52 +00001021 def help_continue(self):
1022 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001023
Tim Peters2344fae2001-01-15 00:50:52 +00001024 def help_cont(self):
1025 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001026
Tim Peters2344fae2001-01-15 00:50:52 +00001027 def help_c(self):
Georg Brandl19564802006-05-10 17:13:20 +00001028 print >>self.stdout, """c(ont(inue))
Tim Peters2344fae2001-01-15 00:50:52 +00001029Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001030
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001031 def help_jump(self):
1032 self.help_j()
1033
1034 def help_j(self):
Georg Brandl19564802006-05-10 17:13:20 +00001035 print >>self.stdout, """j(ump) lineno
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001036Set the next line that will be executed."""
1037
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001038 def help_debug(self):
Georg Brandl19564802006-05-10 17:13:20 +00001039 print >>self.stdout, """debug code
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001040Enter a recursive debugger that steps through the code argument
1041(which is an arbitrary expression or statement to be executed
1042in the current environment)."""
1043
Tim Peters2344fae2001-01-15 00:50:52 +00001044 def help_list(self):
1045 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001046
Tim Peters2344fae2001-01-15 00:50:52 +00001047 def help_l(self):
Georg Brandl19564802006-05-10 17:13:20 +00001048 print >>self.stdout, """l(ist) [first [,last]]
Tim Peters2344fae2001-01-15 00:50:52 +00001049List source code for the current file.
1050Without arguments, list 11 lines around the current line
1051or continue the previous listing.
1052With one argument, list 11 lines starting at that line.
1053With two arguments, list the given range;
1054if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001055
Tim Peters2344fae2001-01-15 00:50:52 +00001056 def help_args(self):
1057 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001058
Tim Peters2344fae2001-01-15 00:50:52 +00001059 def help_a(self):
Georg Brandl19564802006-05-10 17:13:20 +00001060 print >>self.stdout, """a(rgs)
Tim Peters2344fae2001-01-15 00:50:52 +00001061Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001062
Tim Peters2344fae2001-01-15 00:50:52 +00001063 def help_p(self):
Georg Brandl19564802006-05-10 17:13:20 +00001064 print >>self.stdout, """p expression
Tim Peters2344fae2001-01-15 00:50:52 +00001065Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001066
Barry Warsaw210bd202002-11-05 22:40:20 +00001067 def help_pp(self):
Georg Brandl19564802006-05-10 17:13:20 +00001068 print >>self.stdout, """pp expression
Barry Warsaw210bd202002-11-05 22:40:20 +00001069Pretty-print the value of the expression."""
1070
Tim Peters2344fae2001-01-15 00:50:52 +00001071 def help_exec(self):
Georg Brandl19564802006-05-10 17:13:20 +00001072 print >>self.stdout, """(!) statement
Tim Peters2344fae2001-01-15 00:50:52 +00001073Execute the (one-line) statement in the context of
1074the current stack frame.
1075The exclamation point can be omitted unless the first word
1076of the statement resembles a debugger command.
1077To assign to a global variable you must always prefix the
1078command with a 'global' command, e.g.:
1079(Pdb) global list_options; list_options = ['-l']
1080(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001081
Georg Brandl8e84c652007-03-13 21:08:15 +00001082 def help_run(self):
1083 print """run [args...]
1084Restart the debugged python program. If a string is supplied, it is
1085splitted with "shlex" and the result is used as the new sys.argv.
1086History, breakpoints, actions and debugger options are preserved.
1087"restart" is an alias for "run"."""
1088
1089 help_restart = help_run
1090
Tim Peters2344fae2001-01-15 00:50:52 +00001091 def help_quit(self):
1092 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001093
Tim Peters2344fae2001-01-15 00:50:52 +00001094 def help_q(self):
Georg Brandl19564802006-05-10 17:13:20 +00001095 print >>self.stdout, """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +00001096The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001097
Guido van Rossumd1c08f32002-04-15 00:48:24 +00001098 help_exit = help_q
1099
Tim Peters2344fae2001-01-15 00:50:52 +00001100 def help_whatis(self):
Georg Brandl19564802006-05-10 17:13:20 +00001101 print >>self.stdout, """whatis arg
Tim Peters2344fae2001-01-15 00:50:52 +00001102Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001103
Tim Peters2344fae2001-01-15 00:50:52 +00001104 def help_EOF(self):
Georg Brandl19564802006-05-10 17:13:20 +00001105 print >>self.stdout, """EOF
Tim Peters2344fae2001-01-15 00:50:52 +00001106Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001107
Tim Peters2344fae2001-01-15 00:50:52 +00001108 def help_alias(self):
Georg Brandl58152202009-05-05 09:06:02 +00001109 print >>self.stdout, """alias [name [command [parameter parameter ...]]]
Tim Peters2344fae2001-01-15 00:50:52 +00001110Creates an alias called 'name' the executes 'command'. The command
1111must *not* be enclosed in quotes. Replaceable parameters are
1112indicated by %1, %2, and so on, while %* is replaced by all the
1113parameters. If no command is given, the current alias for name
1114is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +00001115
Tim Peters2344fae2001-01-15 00:50:52 +00001116Aliases may be nested and can contain anything that can be
1117legally typed at the pdb prompt. Note! You *can* override
1118internal pdb commands with aliases! Those internal commands
1119are then hidden until the alias is removed. Aliasing is recursively
1120applied to the first word of the command line; all other words
1121in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +00001122
Tim Peters2344fae2001-01-15 00:50:52 +00001123Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +00001124
Tim Peters2344fae2001-01-15 00:50:52 +00001125#Print instance variables (usage "pi classInst")
1126alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +00001127
Tim Peters2344fae2001-01-15 00:50:52 +00001128#Print instance variables in self
1129alias ps pi self
1130"""
Guido van Rossum2424f851998-09-11 22:50:09 +00001131
Tim Peters2344fae2001-01-15 00:50:52 +00001132 def help_unalias(self):
Georg Brandl19564802006-05-10 17:13:20 +00001133 print >>self.stdout, """unalias name
Tim Peters2344fae2001-01-15 00:50:52 +00001134Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001135
Martin v. Löwisbd30f522006-04-17 17:08:37 +00001136 def help_commands(self):
Georg Brandl19564802006-05-10 17:13:20 +00001137 print >>self.stdout, """commands [bpnumber]
Martin v. Löwisbd30f522006-04-17 17:08:37 +00001138(com) ...
1139(com) end
1140(Pdb)
1141
1142Specify a list of commands for breakpoint number bpnumber. The
1143commands themselves appear on the following lines. Type a line
1144containing just 'end' to terminate the commands.
1145
1146To remove all commands from a breakpoint, type commands and
1147follow it immediately with end; that is, give no commands.
1148
1149With no bpnumber argument, commands refers to the last
1150breakpoint set.
1151
1152You can use breakpoint commands to start your program up again.
1153Simply use the continue command, or step, or any other
1154command that resumes execution.
1155
1156Specifying any command resuming execution (currently continue,
1157step, next, return, jump, quit and their abbreviations) terminates
1158the command list (as if that command was immediately followed by end).
1159This is because any time you resume execution
Martin v. Löwisf62eee12006-04-17 17:37:09 +00001160(even with a simple next or step), you may encounter
Martin v. Löwisbd30f522006-04-17 17:08:37 +00001161another breakpoint--which could have its own command list, leading to
1162ambiguities about which list to execute.
1163
1164 If you use the 'silent' command in the command list, the
1165usual message about stopping at a breakpoint is not printed. This may
1166be desirable for breakpoints that are to print a specific message and
1167then continue. If none of the other commands print anything, you
1168see no sign that the breakpoint was reached.
1169"""
1170
Tim Peters2344fae2001-01-15 00:50:52 +00001171 def help_pdb(self):
1172 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001173
Tim Peters2344fae2001-01-15 00:50:52 +00001174 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001175 """Helper function for break/clear parsing -- may be overridden.
1176
1177 lookupmodule() translates (possibly incomplete) file or module name
1178 into an absolute file name.
1179 """
1180 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001181 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001182 f = os.path.join(sys.path[0], filename)
1183 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1184 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001185 root, ext = os.path.splitext(filename)
1186 if ext == '':
1187 filename = filename + '.py'
1188 if os.path.isabs(filename):
1189 return filename
1190 for dirname in sys.path:
1191 while os.path.islink(dirname):
1192 dirname = os.readlink(dirname)
1193 fullname = os.path.join(dirname, filename)
1194 if os.path.exists(fullname):
1195 return fullname
1196 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001197
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001198 def _runscript(self, filename):
Georg Brandlb6ae6aa2007-03-13 21:58:44 +00001199 # The script has to run in __main__ namespace (or imports from
1200 # __main__ will break).
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001201 #
Georg Brandlb6ae6aa2007-03-13 21:58:44 +00001202 # So we clear up the __main__ and set several special variables
1203 # (this gets rid of pdb's globals and cleans old variables on restarts).
1204 import __main__
1205 __main__.__dict__.clear()
1206 __main__.__dict__.update({"__name__" : "__main__",
1207 "__file__" : filename,
1208 "__builtins__": __builtins__,
1209 })
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001210
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001211 # When bdb sets tracing, a number of call and line events happens
1212 # BEFORE debugger even reaches user's code (and the exact sequence of
1213 # events depends on python version). So we take special measures to
1214 # avoid stopping before we reach the main script (see user_line and
1215 # user_call for details).
1216 self._wait_for_mainpyfile = 1
1217 self.mainpyfile = self.canonic(filename)
1218 self._user_requested_quit = 0
1219 statement = 'execfile( "%s")' % filename
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001220 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001221
Guido van Rossum35771131992-09-08 11:59:04 +00001222# Simplified interface
1223
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001224def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001225 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001226
1227def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001228 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001229
1230def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001231 # B/W compatibility
1232 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001233
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001234def runcall(*args, **kwds):
1235 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001236
Guido van Rossumb6775db1994-08-01 11:34:53 +00001237def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001238 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001239
1240# Post-Mortem interface
1241
Facundo Batistac54aec12008-03-08 16:50:27 +00001242def post_mortem(t=None):
1243 # handling the default
1244 if t is None:
1245 # sys.exc_info() returns (type, value, traceback) if an exception is
1246 # being handled, otherwise it returns None
1247 t = sys.exc_info()[2]
1248 if t is None:
1249 raise ValueError("A valid traceback must be passed if no "
1250 "exception is being handled")
1251
Tim Peters2344fae2001-01-15 00:50:52 +00001252 p = Pdb()
1253 p.reset()
Benjamin Petersonc18574c2008-10-22 21:16:34 +00001254 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001255
1256def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001257 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001258
1259
1260# Main program for testing
1261
Guido van Rossum23efba41992-01-27 16:58:47 +00001262TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001263
Guido van Rossum921c8241992-01-10 14:54:42 +00001264def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001265 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001266
1267# print help
1268def help():
Tim Peters2344fae2001-01-15 00:50:52 +00001269 for dirname in sys.path:
1270 fullname = os.path.join(dirname, 'pdb.doc')
1271 if os.path.exists(fullname):
1272 sts = os.system('${PAGER-more} '+fullname)
1273 if sts: print '*** Pager exit status:', sts
1274 break
1275 else:
1276 print 'Sorry, can\'t find the help file "pdb.doc"',
1277 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +00001278
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001279def main():
Benjamin Peterson13be2cf2008-03-26 11:57:47 +00001280 if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
Tim Peters2344fae2001-01-15 00:50:52 +00001281 print "usage: pdb.py scriptfile [arg] ..."
1282 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001283
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001284 mainpyfile = sys.argv[1] # Get script filename
1285 if not os.path.exists(mainpyfile):
1286 print 'Error:', mainpyfile, 'does not exist'
Tim Peters2344fae2001-01-15 00:50:52 +00001287 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001288
Tim Peters2344fae2001-01-15 00:50:52 +00001289 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001290
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001291 # Replace pdb's dir with script's dir in front of module search path.
1292 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001293
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001294 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1295 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl58152202009-05-05 09:06:02 +00001296 # changed by the user from the command line. There is a "restart" command
1297 # which allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001298 pdb = Pdb()
1299 while 1:
1300 try:
1301 pdb._runscript(mainpyfile)
1302 if pdb._user_requested_quit:
1303 break
Tim Peterse718f612004-10-12 21:51:32 +00001304 print "The program finished and will be restarted"
Georg Brandl8e84c652007-03-13 21:08:15 +00001305 except Restart:
1306 print "Restarting", mainpyfile, "with arguments:"
1307 print "\t" + " ".join(sys.argv[1:])
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001308 except SystemExit:
1309 # In most cases SystemExit does not warrant a post-mortem session.
1310 print "The program exited via sys.exit(). Exit status: ",
1311 print sys.exc_info()[1]
1312 except:
1313 traceback.print_exc()
1314 print "Uncaught exception. Entering post mortem debugging"
1315 print "Running 'cont' or 'step' will restart the program"
1316 t = sys.exc_info()[2]
Benjamin Petersonc18574c2008-10-22 21:16:34 +00001317 pdb.interaction(None, t)
Georg Brandl58152202009-05-05 09:06:02 +00001318 print "Post mortem debugger finished. The " + mainpyfile + \
1319 " will be restarted"
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001320
1321
1322# When invoked as main program, invoke the debugger on a script
Georg Brandlb6ae6aa2007-03-13 21:58:44 +00001323if __name__ == '__main__':
1324 import pdb
1325 pdb.main()