blob: 1cd6706914bbca80e3ddf50332909d6be686ec6e [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
Gregory P. Smith56fe6562010-05-08 23:38:49 +000016import signal
Georg Brandl8e84c652007-03-13 21:08:15 +000017
18
19class Restart(Exception):
20 """Causes a debugger to be restarted for the debugged python program."""
21 pass
22
Guido van Rossumef1b41b2002-09-10 21:57:14 +000023# Create a custom safe Repr instance and increase its maxstring.
24# The default of 30 truncates error messages too easily.
25_repr = Repr()
26_repr.maxstring = 200
27_saferepr = _repr.repr
28
Skip Montanaro352674d2001-02-07 23:14:30 +000029__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
30 "post_mortem", "help"]
31
Barry Warsaw2bee8fe1999-09-09 16:32:41 +000032def find_function(funcname, filename):
Andrew M. Kuchlinge6728252006-09-05 13:19:18 +000033 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
Tim Peters2344fae2001-01-15 00:50:52 +000034 try:
35 fp = open(filename)
36 except IOError:
37 return None
38 # consumer of this info expects the first line to be 1
39 lineno = 1
40 answer = None
41 while 1:
42 line = fp.readline()
43 if line == '':
44 break
45 if cre.match(line):
46 answer = funcname, filename, lineno
47 break
48 lineno = lineno + 1
49 fp.close()
50 return answer
Guido van Rossum921c8241992-01-10 14:54:42 +000051
52
Guido van Rossuma558e371994-11-10 22:27:35 +000053# Interaction prompt line will separate file and call info from code
54# text using value of line_prefix string. A newline and arrow may
55# be to your liking. You can set it once pdb is imported using the
56# command "pdb.line_prefix = '\n% '".
Tim Peters2344fae2001-01-15 00:50:52 +000057# line_prefix = ': ' # Use this to get the old situation back
58line_prefix = '\n-> ' # Probably a better default
Guido van Rossuma558e371994-11-10 22:27:35 +000059
Guido van Rossum23efba41992-01-27 16:58:47 +000060class Pdb(bdb.Bdb, cmd.Cmd):
Guido van Rossum2424f851998-09-11 22:50:09 +000061
Georg Brandl4d4313d2009-05-05 08:54:11 +000062 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None):
63 bdb.Bdb.__init__(self, skip=skip)
Georg Brandl19564802006-05-10 17:13:20 +000064 cmd.Cmd.__init__(self, completekey, stdin, stdout)
65 if stdout:
66 self.use_rawinput = 0
Tim Peters2344fae2001-01-15 00:50:52 +000067 self.prompt = '(Pdb) '
68 self.aliases = {}
Johannes Gijsbers25b38c82004-10-12 18:12:09 +000069 self.mainpyfile = ''
70 self._wait_for_mainpyfile = 0
Tim Peters2344fae2001-01-15 00:50:52 +000071 # Try to load readline if it exists
72 try:
73 import readline
74 except ImportError:
75 pass
Gregory P. Smith56fe6562010-05-08 23:38:49 +000076 self.allow_kbdint = False
77 signal.signal(signal.SIGINT, self.sigint_handler)
Guido van Rossum2424f851998-09-11 22:50:09 +000078
Tim Peters2344fae2001-01-15 00:50:52 +000079 # Read $HOME/.pdbrc and ./.pdbrc
80 self.rcLines = []
Raymond Hettinger54f02222002-06-01 14:18:47 +000081 if 'HOME' in os.environ:
Tim Peters2344fae2001-01-15 00:50:52 +000082 envHome = os.environ['HOME']
83 try:
84 rcFile = open(os.path.join(envHome, ".pdbrc"))
85 except IOError:
86 pass
87 else:
88 for line in rcFile.readlines():
89 self.rcLines.append(line)
90 rcFile.close()
91 try:
92 rcFile = open(".pdbrc")
93 except IOError:
94 pass
95 else:
96 for line in rcFile.readlines():
97 self.rcLines.append(line)
98 rcFile.close()
Guido van Rossum23efba41992-01-27 16:58:47 +000099
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000100 self.commands = {} # associates a command list to breakpoint numbers
Georg Brandle361bcb2009-04-01 23:32:17 +0000101 self.commands_doprompt = {} # for each bp num, tells if the prompt
102 # must be disp. after execing the cmd list
103 self.commands_silent = {} # for each bp num, tells if the stack trace
104 # must be disp. after execing the cmd list
105 self.commands_defining = False # True while in the process of defining
106 # a command list
107 self.commands_bnum = None # The breakpoint number for which we are
108 # defining a list
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000109
Gregory P. Smith56fe6562010-05-08 23:38:49 +0000110 def sigint_handler(self, signum, frame):
111 if self.allow_kbdint:
112 raise KeyboardInterrupt()
113 print >>self.stdout, "\nProgram interrupted. (Use 'cont' to resume)."
114 self.set_step()
115 self.set_trace(frame)
116
Tim Peters2344fae2001-01-15 00:50:52 +0000117 def reset(self):
118 bdb.Bdb.reset(self)
119 self.forget()
Guido van Rossum23efba41992-01-27 16:58:47 +0000120
Tim Peters2344fae2001-01-15 00:50:52 +0000121 def forget(self):
122 self.lineno = None
123 self.stack = []
124 self.curindex = 0
125 self.curframe = None
Guido van Rossum2424f851998-09-11 22:50:09 +0000126
Tim Peters2344fae2001-01-15 00:50:52 +0000127 def setup(self, f, t):
128 self.forget()
129 self.stack, self.curindex = self.get_stack(f, t)
130 self.curframe = self.stack[self.curindex][0]
Georg Brandle361bcb2009-04-01 23:32:17 +0000131 # The f_locals dictionary is updated from the actual frame
132 # locals whenever the .f_locals accessor is called, so we
133 # cache it here to ensure that modifications are not overwritten.
134 self.curframe_locals = self.curframe.f_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000135 self.execRcLines()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000136
Tim Peters2344fae2001-01-15 00:50:52 +0000137 # Can be executed earlier than 'setup' if desired
138 def execRcLines(self):
139 if self.rcLines:
140 # Make local copy because of recursion
141 rcLines = self.rcLines
142 # executed only once
143 self.rcLines = []
144 for line in rcLines:
145 line = line[:-1]
Guido van Rossum08454592002-07-12 13:10:53 +0000146 if len(line) > 0 and line[0] != '#':
147 self.onecmd(line)
Guido van Rossum2424f851998-09-11 22:50:09 +0000148
Tim Peters280488b2002-08-23 18:19:30 +0000149 # Override Bdb methods
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000150
151 def user_call(self, frame, argument_list):
152 """This method is called when there is the remote possibility
153 that we ever need to stop in this function."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000154 if self._wait_for_mainpyfile:
155 return
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000156 if self.stop_here(frame):
Georg Brandl19564802006-05-10 17:13:20 +0000157 print >>self.stdout, '--Call--'
Michael W. Hudson01eb85c2003-01-31 17:48:29 +0000158 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000159
Tim Peters2344fae2001-01-15 00:50:52 +0000160 def user_line(self, frame):
161 """This function is called when we stop or break at this line."""
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000162 if self._wait_for_mainpyfile:
163 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
164 or frame.f_lineno<= 0):
165 return
166 self._wait_for_mainpyfile = 0
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000167 if self.bp_commands(frame):
168 self.interaction(frame, None)
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000169
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000170 def bp_commands(self,frame):
Georg Brandl58152202009-05-05 09:06:02 +0000171 """Call every command that was set for the current active breakpoint
172 (if there is one).
173
174 Returns True if the normal interaction function must be called,
175 False otherwise."""
176 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
177 if getattr(self, "currentbp", False) and \
178 self.currentbp in self.commands:
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000179 currentbp = self.currentbp
180 self.currentbp = 0
181 lastcmd_back = self.lastcmd
182 self.setup(frame, None)
183 for line in self.commands[currentbp]:
184 self.onecmd(line)
185 self.lastcmd = lastcmd_back
186 if not self.commands_silent[currentbp]:
187 self.print_stack_entry(self.stack[self.curindex])
188 if self.commands_doprompt[currentbp]:
Gregory P. Smith56fe6562010-05-08 23:38:49 +0000189 self._cmdloop()
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000190 self.forget()
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000191 return
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000192 return 1
Guido van Rossum9e1ee971997-07-11 13:43:53 +0000193
Tim Peters2344fae2001-01-15 00:50:52 +0000194 def user_return(self, frame, return_value):
195 """This function is called when a return trap is set here."""
196 frame.f_locals['__return__'] = return_value
Georg Brandl19564802006-05-10 17:13:20 +0000197 print >>self.stdout, '--Return--'
Tim Peters2344fae2001-01-15 00:50:52 +0000198 self.interaction(frame, None)
Guido van Rossum2424f851998-09-11 22:50:09 +0000199
Brett Cannonc6a30ec2008-08-01 01:36:47 +0000200 def user_exception(self, frame, exc_info):
201 exc_type, exc_value, exc_traceback = exc_info
Tim Peters2344fae2001-01-15 00:50:52 +0000202 """This function is called if an exception occurs,
203 but only if we are to stop at or just below this level."""
204 frame.f_locals['__exception__'] = exc_type, exc_value
205 if type(exc_type) == type(''):
206 exc_type_name = exc_type
207 else: exc_type_name = exc_type.__name__
Georg Brandl19564802006-05-10 17:13:20 +0000208 print >>self.stdout, exc_type_name + ':', _saferepr(exc_value)
Tim Peters2344fae2001-01-15 00:50:52 +0000209 self.interaction(frame, exc_traceback)
Guido van Rossum2424f851998-09-11 22:50:09 +0000210
Tim Peters2344fae2001-01-15 00:50:52 +0000211 # General interaction function
Gregory P. Smith56fe6562010-05-08 23:38:49 +0000212 def _cmdloop(self):
213 while 1:
214 try:
215 # keyboard interrupts allow for an easy way to interrupt
216 # the current command
217 self.allow_kbdint = True
218 self.cmdloop()
219 self.allow_kbdint = False
220 break
221 except KeyboardInterrupt:
222 print >>self.stdout, '--KeyboardInterrupt--'
Tim Peters2344fae2001-01-15 00:50:52 +0000223
224 def interaction(self, frame, traceback):
225 self.setup(frame, traceback)
226 self.print_stack_entry(self.stack[self.curindex])
Gregory P. Smith56fe6562010-05-08 23:38:49 +0000227 self._cmdloop()
Tim Peters2344fae2001-01-15 00:50:52 +0000228 self.forget()
229
Georg Brandl58b8b952009-04-01 21:54:21 +0000230 def displayhook(self, obj):
231 """Custom displayhook for the exec in default(), which prevents
232 assignment of the _ variable in the builtins.
233 """
Georg Brandl69dfe8d2009-09-16 16:36:39 +0000234 # reproduce the behavior of the standard displayhook, not printing None
235 if obj is not None:
236 print repr(obj)
Georg Brandl58b8b952009-04-01 21:54:21 +0000237
Tim Peters2344fae2001-01-15 00:50:52 +0000238 def default(self, line):
239 if line[:1] == '!': line = line[1:]
Georg Brandle361bcb2009-04-01 23:32:17 +0000240 locals = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000241 globals = self.curframe.f_globals
242 try:
243 code = compile(line + '\n', '<stdin>', 'single')
Amaury Forgeot d'Arcff0f2672008-01-15 21:25:11 +0000244 save_stdout = sys.stdout
245 save_stdin = sys.stdin
Georg Brandl58b8b952009-04-01 21:54:21 +0000246 save_displayhook = sys.displayhook
Guido van Rossumcad37242008-01-15 17:59:29 +0000247 try:
248 sys.stdin = self.stdin
249 sys.stdout = self.stdout
Georg Brandl58b8b952009-04-01 21:54:21 +0000250 sys.displayhook = self.displayhook
Guido van Rossumcad37242008-01-15 17:59:29 +0000251 exec code in globals, locals
252 finally:
253 sys.stdout = save_stdout
254 sys.stdin = save_stdin
Georg Brandl58b8b952009-04-01 21:54:21 +0000255 sys.displayhook = save_displayhook
Tim Peters2344fae2001-01-15 00:50:52 +0000256 except:
257 t, v = sys.exc_info()[:2]
258 if type(t) == type(''):
259 exc_type_name = t
260 else: exc_type_name = t.__name__
Georg Brandl19564802006-05-10 17:13:20 +0000261 print >>self.stdout, '***', exc_type_name + ':', v
Tim Peters2344fae2001-01-15 00:50:52 +0000262
263 def precmd(self, line):
264 """Handle alias expansion and ';;' separator."""
Guido van Rossum08454592002-07-12 13:10:53 +0000265 if not line.strip():
Tim Peters2344fae2001-01-15 00:50:52 +0000266 return line
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000267 args = line.split()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000268 while args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000269 line = self.aliases[args[0]]
270 ii = 1
271 for tmpArg in args[1:]:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000272 line = line.replace("%" + str(ii),
Tim Peters2344fae2001-01-15 00:50:52 +0000273 tmpArg)
274 ii = ii + 1
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000275 line = line.replace("%*", ' '.join(args[1:]))
276 args = line.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000277 # split into ';;' separated commands
278 # unless it's an alias command
279 if args[0] != 'alias':
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000280 marker = line.find(';;')
Tim Peters2344fae2001-01-15 00:50:52 +0000281 if marker >= 0:
282 # queue up everything after marker
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000283 next = line[marker+2:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000284 self.cmdqueue.append(next)
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000285 line = line[:marker].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000286 return line
287
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000288 def onecmd(self, line):
289 """Interpret the argument as though it had been typed in response
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000290 to the prompt.
291
Andrew M. Kuchling9aed98f2006-07-27 12:18:20 +0000292 Checks whether this line is typed at the normal prompt or in
Tim Petersdaea0352006-07-27 15:11:00 +0000293 a breakpoint command list definition.
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000294 """
295 if not self.commands_defining:
296 return cmd.Cmd.onecmd(self, line)
297 else:
298 return self.handle_command_def(line)
299
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000300 def handle_command_def(self,line):
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000301 """ Handles one command line during command list definition. """
302 cmd, arg, line = self.parseline(line)
303 if cmd == 'silent':
304 self.commands_silent[self.commands_bnum] = True
305 return # continue to handle other cmd def in the cmd list
306 elif cmd == 'end':
307 self.cmdqueue = []
308 return 1 # end of cmd list
309 cmdlist = self.commands[self.commands_bnum]
310 if (arg):
311 cmdlist.append(cmd+' '+arg)
312 else:
313 cmdlist.append(cmd)
314 # Determine if we must stop
315 try:
316 func = getattr(self, 'do_' + cmd)
317 except AttributeError:
318 func = self.default
Georg Brandl58152202009-05-05 09:06:02 +0000319 # one of the resuming commands
320 if func.func_name in self.commands_resuming:
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000321 self.commands_doprompt[self.commands_bnum] = False
322 self.cmdqueue = []
323 return 1
Martin v. Löwis1a00e182006-04-17 19:18:18 +0000324 return
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000325
Tim Peters2344fae2001-01-15 00:50:52 +0000326 # Command definitions, called by cmdloop()
327 # The argument is the remaining string on the command line
328 # Return true to exit from the command loop
329
330 do_h = cmd.Cmd.do_help
331
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000332 def do_commands(self, arg):
Georg Brandl58152202009-05-05 09:06:02 +0000333 """Defines a list of commands associated to a breakpoint.
334
335 Those commands will be executed whenever the breakpoint causes
336 the program to stop execution."""
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000337 if not arg:
338 bnum = len(bdb.Breakpoint.bpbynumber)-1
339 else:
340 try:
341 bnum = int(arg)
342 except:
Georg Brandl58152202009-05-05 09:06:02 +0000343 print >>self.stdout, "Usage : commands [bnum]\n ..." \
344 "\n end"
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000345 return
346 self.commands_bnum = bnum
347 self.commands[bnum] = []
348 self.commands_doprompt[bnum] = True
349 self.commands_silent[bnum] = False
350 prompt_back = self.prompt
351 self.prompt = '(com) '
352 self.commands_defining = True
Gregory P. Smith56fe6562010-05-08 23:38:49 +0000353 try:
354 self.cmdloop()
355 except (KeyboardInterrupt, IOError):
356 # It appears that that when pdb is reading input from a pipe
357 # we may get IOErrors, rather than KeyboardInterrupt.
358 # Now discard all the commands entered so far (essentially undo
359 # any effect of this "commands" cmd)
360 self.commands.pop(bnum)
361 self.commands_doprompt.pop(bnum)
362 self.commands_silent.pop(bnum)
363 # this will get caught by the _cmdloop and pdb will reenter
364 # the main command loop
365 raise KeyboardInterrupt()
366 finally:
367 self.commands_defining = False
368 self.prompt = prompt_back
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000369
Tim Peters2344fae2001-01-15 00:50:52 +0000370 def do_break(self, arg, temporary = 0):
371 # break [ ([filename:]lineno | function) [, "condition"] ]
372 if not arg:
373 if self.breaks: # There's at least one
Georg Brandl19564802006-05-10 17:13:20 +0000374 print >>self.stdout, "Num Type Disp Enb Where"
Tim Peters2344fae2001-01-15 00:50:52 +0000375 for bp in bdb.Breakpoint.bpbynumber:
376 if bp:
Georg Brandl19564802006-05-10 17:13:20 +0000377 bp.bpprint(self.stdout)
Tim Peters2344fae2001-01-15 00:50:52 +0000378 return
379 # parse arguments; comma has lowest precedence
380 # and cannot occur in filename
381 filename = None
382 lineno = None
383 cond = None
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000384 comma = arg.find(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000385 if comma > 0:
386 # parse stuff after comma: "condition"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000387 cond = arg[comma+1:].lstrip()
388 arg = arg[:comma].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000389 # parse stuff before comma: [filename:]lineno | function
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000390 colon = arg.rfind(':')
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000391 funcname = None
Tim Peters2344fae2001-01-15 00:50:52 +0000392 if colon >= 0:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000393 filename = arg[:colon].rstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000394 f = self.lookupmodule(filename)
395 if not f:
Georg Brandl19564802006-05-10 17:13:20 +0000396 print >>self.stdout, '*** ', repr(filename),
397 print >>self.stdout, 'not found from sys.path'
Tim Peters2344fae2001-01-15 00:50:52 +0000398 return
399 else:
400 filename = f
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000401 arg = arg[colon+1:].lstrip()
Tim Peters2344fae2001-01-15 00:50:52 +0000402 try:
403 lineno = int(arg)
404 except ValueError, msg:
Georg Brandl19564802006-05-10 17:13:20 +0000405 print >>self.stdout, '*** Bad lineno:', arg
Tim Peters2344fae2001-01-15 00:50:52 +0000406 return
407 else:
408 # no colon; can be lineno or function
409 try:
410 lineno = int(arg)
411 except ValueError:
412 try:
413 func = eval(arg,
414 self.curframe.f_globals,
Georg Brandle361bcb2009-04-01 23:32:17 +0000415 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000416 except:
417 func = arg
418 try:
419 if hasattr(func, 'im_func'):
420 func = func.im_func
421 code = func.func_code
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000422 #use co_name to identify the bkpt (function names
423 #could be aliased, but co_name is invariant)
424 funcname = code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000425 lineno = code.co_firstlineno
426 filename = code.co_filename
427 except:
428 # last thing to try
429 (ok, filename, ln) = self.lineinfo(arg)
430 if not ok:
Georg Brandl19564802006-05-10 17:13:20 +0000431 print >>self.stdout, '*** The specified object',
432 print >>self.stdout, repr(arg),
433 print >>self.stdout, 'is not a function'
434 print >>self.stdout, 'or was not found along sys.path.'
Tim Peters2344fae2001-01-15 00:50:52 +0000435 return
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000436 funcname = ok # ok contains a function name
Tim Peters2344fae2001-01-15 00:50:52 +0000437 lineno = int(ln)
438 if not filename:
439 filename = self.defaultFile()
440 # Check for reasonable breakpoint
441 line = self.checkline(filename, lineno)
442 if line:
443 # now set the break point
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000444 err = self.set_break(filename, line, temporary, cond, funcname)
Georg Brandl19564802006-05-10 17:13:20 +0000445 if err: print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000446 else:
447 bp = self.get_breaks(filename, line)[-1]
Georg Brandl19564802006-05-10 17:13:20 +0000448 print >>self.stdout, "Breakpoint %d at %s:%d" % (bp.number,
449 bp.file,
450 bp.line)
Tim Peters2344fae2001-01-15 00:50:52 +0000451
452 # To be overridden in derived debuggers
453 def defaultFile(self):
454 """Produce a reasonable default."""
455 filename = self.curframe.f_code.co_filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000456 if filename == '<string>' and self.mainpyfile:
457 filename = self.mainpyfile
Tim Peters2344fae2001-01-15 00:50:52 +0000458 return filename
459
460 do_b = do_break
461
462 def do_tbreak(self, arg):
463 self.do_break(arg, 1)
464
465 def lineinfo(self, identifier):
466 failed = (None, None, None)
467 # Input is identifier, may be in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000468 idstring = identifier.split("'")
Tim Peters2344fae2001-01-15 00:50:52 +0000469 if len(idstring) == 1:
470 # not in single quotes
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000471 id = idstring[0].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000472 elif len(idstring) == 3:
473 # quoted
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000474 id = idstring[1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000475 else:
476 return failed
477 if id == '': return failed
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000478 parts = id.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000479 # Protection for derived debuggers
480 if parts[0] == 'self':
481 del parts[0]
482 if len(parts) == 0:
483 return failed
484 # Best first guess at file to look at
485 fname = self.defaultFile()
486 if len(parts) == 1:
487 item = parts[0]
488 else:
489 # More than one part.
490 # First is module, second is method/class
491 f = self.lookupmodule(parts[0])
492 if f:
493 fname = f
494 item = parts[1]
495 answer = find_function(item, fname)
496 return answer or failed
497
498 def checkline(self, filename, lineno):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000499 """Check whether specified line seems to be executable.
Tim Peters2344fae2001-01-15 00:50:52 +0000500
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000501 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
502 line or EOF). Warning: testing is not comprehensive.
503 """
Nick Coghlana2053472008-12-14 10:54:50 +0000504 line = linecache.getline(filename, lineno, self.curframe.f_globals)
Tim Peters2344fae2001-01-15 00:50:52 +0000505 if not line:
Georg Brandl19564802006-05-10 17:13:20 +0000506 print >>self.stdout, 'End of file'
Tim Peters2344fae2001-01-15 00:50:52 +0000507 return 0
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000508 line = line.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000509 # Don't allow setting breakpoint at a blank line
Guido van Rossum08454592002-07-12 13:10:53 +0000510 if (not line or (line[0] == '#') or
511 (line[:3] == '"""') or line[:3] == "'''"):
Georg Brandl19564802006-05-10 17:13:20 +0000512 print >>self.stdout, '*** Blank or comment'
Tim Peters2344fae2001-01-15 00:50:52 +0000513 return 0
Tim Peters2344fae2001-01-15 00:50:52 +0000514 return lineno
515
516 def do_enable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000517 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000518 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000519 try:
520 i = int(i)
521 except ValueError:
Georg Brandl19564802006-05-10 17:13:20 +0000522 print >>self.stdout, 'Breakpoint index %r is not a number' % i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000523 continue
524
525 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Georg Brandl19564802006-05-10 17:13:20 +0000526 print >>self.stdout, 'No breakpoint numbered', i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000527 continue
528
529 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000530 if bp:
531 bp.enable()
532
533 def do_disable(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000534 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000535 for i in args:
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000536 try:
537 i = int(i)
538 except ValueError:
Georg Brandl19564802006-05-10 17:13:20 +0000539 print >>self.stdout, 'Breakpoint index %r is not a number' % i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000540 continue
Tim Petersf545baa2003-06-15 23:26:30 +0000541
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000542 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Georg Brandl19564802006-05-10 17:13:20 +0000543 print >>self.stdout, 'No breakpoint numbered', i
Andrew M. Kuchlingb1f8bab2003-05-22 14:46:12 +0000544 continue
545
546 bp = bdb.Breakpoint.bpbynumber[i]
Tim Peters2344fae2001-01-15 00:50:52 +0000547 if bp:
548 bp.disable()
549
550 def do_condition(self, arg):
551 # arg is breakpoint number and condition
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000552 args = arg.split(' ', 1)
Georg Brandle4980832007-01-22 21:23:41 +0000553 try:
554 bpnum = int(args[0].strip())
555 except ValueError:
556 # something went wrong
557 print >>self.stdout, \
558 'Breakpoint index %r is not a number' % args[0]
Georg Brandlb2783182007-03-11 08:28:46 +0000559 return
Tim Peters2344fae2001-01-15 00:50:52 +0000560 try:
561 cond = args[1]
562 except:
563 cond = None
Collin Winter2faa9e12007-03-11 16:00:20 +0000564 try:
565 bp = bdb.Breakpoint.bpbynumber[bpnum]
566 except IndexError:
567 print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
568 return
Tim Peters2344fae2001-01-15 00:50:52 +0000569 if bp:
570 bp.cond = cond
571 if not cond:
Georg Brandl19564802006-05-10 17:13:20 +0000572 print >>self.stdout, 'Breakpoint', bpnum,
573 print >>self.stdout, 'is now unconditional.'
Tim Peters2344fae2001-01-15 00:50:52 +0000574
575 def do_ignore(self,arg):
576 """arg is bp number followed by ignore count."""
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000577 args = arg.split()
Georg Brandle4980832007-01-22 21:23:41 +0000578 try:
579 bpnum = int(args[0].strip())
580 except ValueError:
581 # something went wrong
582 print >>self.stdout, \
583 'Breakpoint index %r is not a number' % args[0]
Georg Brandlb2783182007-03-11 08:28:46 +0000584 return
Tim Peters2344fae2001-01-15 00:50:52 +0000585 try:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000586 count = int(args[1].strip())
Tim Peters2344fae2001-01-15 00:50:52 +0000587 except:
588 count = 0
Collin Winter2faa9e12007-03-11 16:00:20 +0000589 try:
590 bp = bdb.Breakpoint.bpbynumber[bpnum]
591 except IndexError:
592 print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
593 return
Tim Peters2344fae2001-01-15 00:50:52 +0000594 if bp:
595 bp.ignore = count
Guido van Rossum08454592002-07-12 13:10:53 +0000596 if count > 0:
Tim Peters2344fae2001-01-15 00:50:52 +0000597 reply = 'Will ignore next '
Guido van Rossum08454592002-07-12 13:10:53 +0000598 if count > 1:
Tim Peters2344fae2001-01-15 00:50:52 +0000599 reply = reply + '%d crossings' % count
600 else:
601 reply = reply + '1 crossing'
Georg Brandl19564802006-05-10 17:13:20 +0000602 print >>self.stdout, reply + ' of breakpoint %d.' % bpnum
Tim Peters2344fae2001-01-15 00:50:52 +0000603 else:
Georg Brandl19564802006-05-10 17:13:20 +0000604 print >>self.stdout, 'Will stop next time breakpoint',
605 print >>self.stdout, bpnum, 'is reached.'
Tim Peters2344fae2001-01-15 00:50:52 +0000606
607 def do_clear(self, arg):
608 """Three possibilities, tried in this order:
609 clear -> clear all breaks, ask for confirmation
610 clear file:lineno -> clear all breaks at file:lineno
611 clear bpno bpno ... -> clear breakpoints by number"""
612 if not arg:
613 try:
614 reply = raw_input('Clear all breaks? ')
615 except EOFError:
616 reply = 'no'
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000617 reply = reply.strip().lower()
Tim Peters2344fae2001-01-15 00:50:52 +0000618 if reply in ('y', 'yes'):
619 self.clear_all_breaks()
620 return
621 if ':' in arg:
622 # Make sure it works for "clear C:\foo\bar.py:12"
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000623 i = arg.rfind(':')
Tim Peters2344fae2001-01-15 00:50:52 +0000624 filename = arg[:i]
625 arg = arg[i+1:]
626 try:
627 lineno = int(arg)
Georg Brandl23d9d452006-05-03 18:12:33 +0000628 except ValueError:
Tim Peters2344fae2001-01-15 00:50:52 +0000629 err = "Invalid line number (%s)" % arg
630 else:
631 err = self.clear_break(filename, lineno)
Georg Brandl19564802006-05-10 17:13:20 +0000632 if err: print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000633 return
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000634 numberlist = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000635 for i in numberlist:
Georg Brandl23d9d452006-05-03 18:12:33 +0000636 try:
637 i = int(i)
638 except ValueError:
Georg Brandl19564802006-05-10 17:13:20 +0000639 print >>self.stdout, 'Breakpoint index %r is not a number' % i
Georg Brandl23d9d452006-05-03 18:12:33 +0000640 continue
641
Georg Brandl6d2b3462005-08-24 07:36:17 +0000642 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
Georg Brandl19564802006-05-10 17:13:20 +0000643 print >>self.stdout, 'No breakpoint numbered', i
Georg Brandl6d2b3462005-08-24 07:36:17 +0000644 continue
Tim Peters2344fae2001-01-15 00:50:52 +0000645 err = self.clear_bpbynumber(i)
646 if err:
Georg Brandl19564802006-05-10 17:13:20 +0000647 print >>self.stdout, '***', err
Tim Peters2344fae2001-01-15 00:50:52 +0000648 else:
Georg Brandl19564802006-05-10 17:13:20 +0000649 print >>self.stdout, 'Deleted breakpoint', i
Tim Peters2344fae2001-01-15 00:50:52 +0000650 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
651
652 def do_where(self, arg):
653 self.print_stack_trace()
654 do_w = do_where
Guido van Rossum6bd68352001-01-20 17:57:37 +0000655 do_bt = do_where
Tim Peters2344fae2001-01-15 00:50:52 +0000656
657 def do_up(self, arg):
658 if self.curindex == 0:
Georg Brandl19564802006-05-10 17:13:20 +0000659 print >>self.stdout, '*** Oldest frame'
Tim Peters2344fae2001-01-15 00:50:52 +0000660 else:
661 self.curindex = self.curindex - 1
662 self.curframe = self.stack[self.curindex][0]
Georg Brandl569fc962009-04-02 02:00:01 +0000663 self.curframe_locals = self.curframe.f_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000664 self.print_stack_entry(self.stack[self.curindex])
665 self.lineno = None
666 do_u = do_up
667
668 def do_down(self, arg):
669 if self.curindex + 1 == len(self.stack):
Georg Brandl19564802006-05-10 17:13:20 +0000670 print >>self.stdout, '*** Newest frame'
Tim Peters2344fae2001-01-15 00:50:52 +0000671 else:
672 self.curindex = self.curindex + 1
673 self.curframe = self.stack[self.curindex][0]
Georg Brandl569fc962009-04-02 02:00:01 +0000674 self.curframe_locals = self.curframe.f_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000675 self.print_stack_entry(self.stack[self.curindex])
676 self.lineno = None
677 do_d = do_down
678
Benjamin Peterson98353942008-05-11 14:13:25 +0000679 def do_until(self, arg):
680 self.set_until(self.curframe)
681 return 1
682 do_unt = do_until
683
Tim Peters2344fae2001-01-15 00:50:52 +0000684 def do_step(self, arg):
685 self.set_step()
686 return 1
687 do_s = do_step
688
689 def do_next(self, arg):
690 self.set_next(self.curframe)
691 return 1
692 do_n = do_next
693
Georg Brandl8e84c652007-03-13 21:08:15 +0000694 def do_run(self, arg):
Georg Brandl58152202009-05-05 09:06:02 +0000695 """Restart program by raising an exception to be caught in the main
696 debugger loop. If arguments were given, set them in sys.argv."""
Georg Brandl8e84c652007-03-13 21:08:15 +0000697 if arg:
698 import shlex
699 argv0 = sys.argv[0:1]
700 sys.argv = shlex.split(arg)
701 sys.argv[:0] = argv0
702 raise Restart
703
704 do_restart = do_run
705
Tim Peters2344fae2001-01-15 00:50:52 +0000706 def do_return(self, arg):
707 self.set_return(self.curframe)
708 return 1
709 do_r = do_return
710
711 def do_continue(self, arg):
712 self.set_continue()
713 return 1
714 do_c = do_cont = do_continue
715
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000716 def do_jump(self, arg):
717 if self.curindex + 1 != len(self.stack):
Georg Brandl19564802006-05-10 17:13:20 +0000718 print >>self.stdout, "*** You can only jump within the bottom frame"
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000719 return
720 try:
721 arg = int(arg)
722 except ValueError:
Georg Brandl19564802006-05-10 17:13:20 +0000723 print >>self.stdout, "*** The 'jump' command requires a line number."
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000724 else:
725 try:
726 # Do the jump, fix up our copy of the stack, and display the
727 # new position
728 self.curframe.f_lineno = arg
729 self.stack[self.curindex] = self.stack[self.curindex][0], arg
730 self.print_stack_entry(self.stack[self.curindex])
731 except ValueError, e:
Georg Brandl19564802006-05-10 17:13:20 +0000732 print >>self.stdout, '*** Jump failed:', e
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000733 do_j = do_jump
734
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000735 def do_debug(self, arg):
736 sys.settrace(None)
737 globals = self.curframe.f_globals
Georg Brandle361bcb2009-04-01 23:32:17 +0000738 locals = self.curframe_locals
Guido van Rossumcad37242008-01-15 17:59:29 +0000739 p = Pdb(self.completekey, self.stdin, self.stdout)
Guido van Rossumed538d82003-04-09 19:36:34 +0000740 p.prompt = "(%s) " % self.prompt.strip()
Georg Brandl19564802006-05-10 17:13:20 +0000741 print >>self.stdout, "ENTERING RECURSIVE DEBUGGER"
Guido van Rossumed538d82003-04-09 19:36:34 +0000742 sys.call_tracing(p.run, (arg, globals, locals))
Georg Brandl19564802006-05-10 17:13:20 +0000743 print >>self.stdout, "LEAVING RECURSIVE DEBUGGER"
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000744 sys.settrace(self.trace_dispatch)
745 self.lastcmd = p.lastcmd
746
Tim Peters2344fae2001-01-15 00:50:52 +0000747 def do_quit(self, arg):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000748 self._user_requested_quit = 1
Tim Peters2344fae2001-01-15 00:50:52 +0000749 self.set_quit()
750 return 1
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000751
Tim Peters2344fae2001-01-15 00:50:52 +0000752 do_q = do_quit
Guido van Rossumd1c08f32002-04-15 00:48:24 +0000753 do_exit = do_quit
Tim Peters2344fae2001-01-15 00:50:52 +0000754
Guido van Rossumeef26072003-01-13 21:13:55 +0000755 def do_EOF(self, arg):
Georg Brandl19564802006-05-10 17:13:20 +0000756 print >>self.stdout
Johannes Gijsbers25b38c82004-10-12 18:12:09 +0000757 self._user_requested_quit = 1
Guido van Rossumeef26072003-01-13 21:13:55 +0000758 self.set_quit()
759 return 1
760
Tim Peters2344fae2001-01-15 00:50:52 +0000761 def do_args(self, arg):
Georg Brandle361bcb2009-04-01 23:32:17 +0000762 co = self.curframe.f_code
763 dict = self.curframe_locals
Tim Peters2344fae2001-01-15 00:50:52 +0000764 n = co.co_argcount
765 if co.co_flags & 4: n = n+1
766 if co.co_flags & 8: n = n+1
767 for i in range(n):
768 name = co.co_varnames[i]
Georg Brandl19564802006-05-10 17:13:20 +0000769 print >>self.stdout, name, '=',
770 if name in dict: print >>self.stdout, dict[name]
771 else: print >>self.stdout, "*** undefined ***"
Tim Peters2344fae2001-01-15 00:50:52 +0000772 do_a = do_args
Guido van Rossum2424f851998-09-11 22:50:09 +0000773
Tim Peters2344fae2001-01-15 00:50:52 +0000774 def do_retval(self, arg):
Georg Brandle361bcb2009-04-01 23:32:17 +0000775 if '__return__' in self.curframe_locals:
776 print >>self.stdout, self.curframe_locals['__return__']
Tim Peters2344fae2001-01-15 00:50:52 +0000777 else:
Georg Brandl19564802006-05-10 17:13:20 +0000778 print >>self.stdout, '*** Not yet returned!'
Tim Peters2344fae2001-01-15 00:50:52 +0000779 do_rv = do_retval
Guido van Rossum2424f851998-09-11 22:50:09 +0000780
Barry Warsaw210bd202002-11-05 22:40:20 +0000781 def _getval(self, arg):
Tim Peters2344fae2001-01-15 00:50:52 +0000782 try:
Barry Warsaw210bd202002-11-05 22:40:20 +0000783 return eval(arg, self.curframe.f_globals,
Georg Brandle361bcb2009-04-01 23:32:17 +0000784 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000785 except:
786 t, v = sys.exc_info()[:2]
Barry Warsaw210bd202002-11-05 22:40:20 +0000787 if isinstance(t, str):
Tim Peters2344fae2001-01-15 00:50:52 +0000788 exc_type_name = t
789 else: exc_type_name = t.__name__
Georg Brandl19564802006-05-10 17:13:20 +0000790 print >>self.stdout, '***', exc_type_name + ':', repr(v)
Barry Warsaw210bd202002-11-05 22:40:20 +0000791 raise
Guido van Rossum2424f851998-09-11 22:50:09 +0000792
Barry Warsaw210bd202002-11-05 22:40:20 +0000793 def do_p(self, arg):
794 try:
Georg Brandl19564802006-05-10 17:13:20 +0000795 print >>self.stdout, repr(self._getval(arg))
Barry Warsaw210bd202002-11-05 22:40:20 +0000796 except:
797 pass
798
799 def do_pp(self, arg):
800 try:
Georg Brandl19564802006-05-10 17:13:20 +0000801 pprint.pprint(self._getval(arg), self.stdout)
Barry Warsaw210bd202002-11-05 22:40:20 +0000802 except:
803 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000804
Tim Peters2344fae2001-01-15 00:50:52 +0000805 def do_list(self, arg):
806 self.lastcmd = 'list'
807 last = None
808 if arg:
809 try:
810 x = eval(arg, {}, {})
811 if type(x) == type(()):
812 first, last = x
813 first = int(first)
814 last = int(last)
815 if last < first:
816 # Assume it's a count
817 last = first + last
818 else:
819 first = max(1, int(x) - 5)
820 except:
Georg Brandl19564802006-05-10 17:13:20 +0000821 print >>self.stdout, '*** Error in argument:', repr(arg)
Tim Peters2344fae2001-01-15 00:50:52 +0000822 return
823 elif self.lineno is None:
824 first = max(1, self.curframe.f_lineno - 5)
825 else:
826 first = self.lineno + 1
827 if last is None:
828 last = first + 10
829 filename = self.curframe.f_code.co_filename
830 breaklist = self.get_file_breaks(filename)
831 try:
832 for lineno in range(first, last+1):
Georg Brandl58152202009-05-05 09:06:02 +0000833 line = linecache.getline(filename, lineno,
834 self.curframe.f_globals)
Tim Peters2344fae2001-01-15 00:50:52 +0000835 if not line:
Georg Brandl19564802006-05-10 17:13:20 +0000836 print >>self.stdout, '[EOF]'
Tim Peters2344fae2001-01-15 00:50:52 +0000837 break
838 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000839 s = repr(lineno).rjust(3)
Tim Peters2344fae2001-01-15 00:50:52 +0000840 if len(s) < 4: s = s + ' '
841 if lineno in breaklist: s = s + 'B'
842 else: s = s + ' '
843 if lineno == self.curframe.f_lineno:
844 s = s + '->'
Georg Brandl19564802006-05-10 17:13:20 +0000845 print >>self.stdout, s + '\t' + line,
Tim Peters2344fae2001-01-15 00:50:52 +0000846 self.lineno = lineno
847 except KeyboardInterrupt:
848 pass
849 do_l = do_list
Guido van Rossum2424f851998-09-11 22:50:09 +0000850
Tim Peters2344fae2001-01-15 00:50:52 +0000851 def do_whatis(self, arg):
852 try:
853 value = eval(arg, self.curframe.f_globals,
Georg Brandle361bcb2009-04-01 23:32:17 +0000854 self.curframe_locals)
Tim Peters2344fae2001-01-15 00:50:52 +0000855 except:
856 t, v = sys.exc_info()[:2]
857 if type(t) == type(''):
858 exc_type_name = t
859 else: exc_type_name = t.__name__
Georg Brandl19564802006-05-10 17:13:20 +0000860 print >>self.stdout, '***', exc_type_name + ':', repr(v)
Tim Peters2344fae2001-01-15 00:50:52 +0000861 return
862 code = None
863 # Is it a function?
864 try: code = value.func_code
865 except: pass
866 if code:
Georg Brandl19564802006-05-10 17:13:20 +0000867 print >>self.stdout, 'Function', code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000868 return
869 # Is it an instance method?
870 try: code = value.im_func.func_code
871 except: pass
872 if code:
Georg Brandl19564802006-05-10 17:13:20 +0000873 print >>self.stdout, 'Method', code.co_name
Tim Peters2344fae2001-01-15 00:50:52 +0000874 return
875 # None of the above...
Georg Brandl19564802006-05-10 17:13:20 +0000876 print >>self.stdout, type(value)
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000877
Tim Peters2344fae2001-01-15 00:50:52 +0000878 def do_alias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000879 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000880 if len(args) == 0:
881 keys = self.aliases.keys()
882 keys.sort()
883 for alias in keys:
Georg Brandl19564802006-05-10 17:13:20 +0000884 print >>self.stdout, "%s = %s" % (alias, self.aliases[alias])
Tim Peters2344fae2001-01-15 00:50:52 +0000885 return
Guido van Rossum08454592002-07-12 13:10:53 +0000886 if args[0] in self.aliases and len(args) == 1:
Georg Brandl19564802006-05-10 17:13:20 +0000887 print >>self.stdout, "%s = %s" % (args[0], self.aliases[args[0]])
Tim Peters2344fae2001-01-15 00:50:52 +0000888 else:
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000889 self.aliases[args[0]] = ' '.join(args[1:])
Guido van Rossum23efba41992-01-27 16:58:47 +0000890
Tim Peters2344fae2001-01-15 00:50:52 +0000891 def do_unalias(self, arg):
Eric S. Raymond9b93c5f2001-02-09 07:58:53 +0000892 args = arg.split()
Tim Peters2344fae2001-01-15 00:50:52 +0000893 if len(args) == 0: return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000894 if args[0] in self.aliases:
Tim Peters2344fae2001-01-15 00:50:52 +0000895 del self.aliases[args[0]]
Guido van Rossum00230781993-03-29 11:39:45 +0000896
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000897 #list of all the commands making the program resume execution.
Georg Brandl19564802006-05-10 17:13:20 +0000898 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
899 'do_quit', 'do_jump']
Martin v. Löwisbd30f522006-04-17 17:08:37 +0000900
Tim Peters2344fae2001-01-15 00:50:52 +0000901 # Print a traceback starting at the top stack frame.
902 # The most recently entered frame is printed last;
903 # this is different from dbx and gdb, but consistent with
904 # the Python interpreter's stack trace.
905 # It is also consistent with the up/down commands (which are
906 # compatible with dbx and gdb: up moves towards 'main()'
907 # and down moves towards the most recent stack frame).
Guido van Rossum2424f851998-09-11 22:50:09 +0000908
Tim Peters2344fae2001-01-15 00:50:52 +0000909 def print_stack_trace(self):
910 try:
911 for frame_lineno in self.stack:
912 self.print_stack_entry(frame_lineno)
913 except KeyboardInterrupt:
914 pass
Guido van Rossum2424f851998-09-11 22:50:09 +0000915
Tim Peters2344fae2001-01-15 00:50:52 +0000916 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
917 frame, lineno = frame_lineno
918 if frame is self.curframe:
Georg Brandl19564802006-05-10 17:13:20 +0000919 print >>self.stdout, '>',
Tim Peters2344fae2001-01-15 00:50:52 +0000920 else:
Georg Brandl19564802006-05-10 17:13:20 +0000921 print >>self.stdout, ' ',
922 print >>self.stdout, self.format_stack_entry(frame_lineno,
923 prompt_prefix)
Guido van Rossum2424f851998-09-11 22:50:09 +0000924
Guido van Rossum921c8241992-01-10 14:54:42 +0000925
Tim Peters2344fae2001-01-15 00:50:52 +0000926 # Help methods (derived from pdb.doc)
Guido van Rossum921c8241992-01-10 14:54:42 +0000927
Tim Peters2344fae2001-01-15 00:50:52 +0000928 def help_help(self):
929 self.help_h()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000930
Tim Peters2344fae2001-01-15 00:50:52 +0000931 def help_h(self):
Georg Brandl19564802006-05-10 17:13:20 +0000932 print >>self.stdout, """h(elp)
Tim Peters2344fae2001-01-15 00:50:52 +0000933Without argument, print the list of available commands.
934With a command name as argument, print help about that command
935"help pdb" pipes the full documentation file to the $PAGER
936"help exec" gives help on the ! command"""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000937
Tim Peters2344fae2001-01-15 00:50:52 +0000938 def help_where(self):
939 self.help_w()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000940
Tim Peters2344fae2001-01-15 00:50:52 +0000941 def help_w(self):
Georg Brandl19564802006-05-10 17:13:20 +0000942 print >>self.stdout, """w(here)
Tim Peters2344fae2001-01-15 00:50:52 +0000943Print a stack trace, with the most recent frame at the bottom.
944An arrow indicates the "current frame", which determines the
Guido van Rossum6bd68352001-01-20 17:57:37 +0000945context of most commands. 'bt' is an alias for this command."""
946
947 help_bt = help_w
Guido van Rossumb6775db1994-08-01 11:34:53 +0000948
Tim Peters2344fae2001-01-15 00:50:52 +0000949 def help_down(self):
950 self.help_d()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000951
Tim Peters2344fae2001-01-15 00:50:52 +0000952 def help_d(self):
Georg Brandl19564802006-05-10 17:13:20 +0000953 print >>self.stdout, """d(own)
Tim Peters2344fae2001-01-15 00:50:52 +0000954Move the current frame one level down in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000955(to a newer frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000956
Tim Peters2344fae2001-01-15 00:50:52 +0000957 def help_up(self):
958 self.help_u()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000959
Tim Peters2344fae2001-01-15 00:50:52 +0000960 def help_u(self):
Georg Brandl19564802006-05-10 17:13:20 +0000961 print >>self.stdout, """u(p)
Tim Peters2344fae2001-01-15 00:50:52 +0000962Move the current frame one level up in the stack trace
Johannes Gijsbers34c41202004-08-14 15:19:28 +0000963(to an older frame)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +0000964
Tim Peters2344fae2001-01-15 00:50:52 +0000965 def help_break(self):
966 self.help_b()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000967
Tim Peters2344fae2001-01-15 00:50:52 +0000968 def help_b(self):
Georg Brandl19564802006-05-10 17:13:20 +0000969 print >>self.stdout, """b(reak) ([file:]lineno | function) [, condition]
Tim Peters2344fae2001-01-15 00:50:52 +0000970With a line number argument, set a break there in the current
971file. With a function name, set a break at first executable line
972of that function. Without argument, list all breaks. If a second
973argument is present, it is a string specifying an expression
974which must evaluate to true before the breakpoint is honored.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000975
Tim Peters2344fae2001-01-15 00:50:52 +0000976The line number may be prefixed with a filename and a colon,
977to specify a breakpoint in another file (probably one that
978hasn't been loaded yet). The file is searched for on sys.path;
979the .py suffix may be omitted."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000980
Tim Peters2344fae2001-01-15 00:50:52 +0000981 def help_clear(self):
982 self.help_cl()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000983
Tim Peters2344fae2001-01-15 00:50:52 +0000984 def help_cl(self):
Georg Brandl19564802006-05-10 17:13:20 +0000985 print >>self.stdout, "cl(ear) filename:lineno"
986 print >>self.stdout, """cl(ear) [bpnumber [bpnumber...]]
Tim Peters2344fae2001-01-15 00:50:52 +0000987With a space separated list of breakpoint numbers, clear
988those breakpoints. Without argument, clear all breaks (but
989first ask confirmation). With a filename:lineno argument,
990clear all breaks at that line in that file.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000991
Tim Peters2344fae2001-01-15 00:50:52 +0000992Note that the argument is different from previous versions of
993the debugger (in python distributions 1.5.1 and before) where
994a linenumber was used instead of either filename:lineno or
995breakpoint numbers."""
Guido van Rossumb5699c71998-07-20 23:13:54 +0000996
Tim Peters2344fae2001-01-15 00:50:52 +0000997 def help_tbreak(self):
Georg Brandl58152202009-05-05 09:06:02 +0000998 print >>self.stdout, """tbreak same arguments as break, but breakpoint
999is removed when first hit."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001000
Tim Peters2344fae2001-01-15 00:50:52 +00001001 def help_enable(self):
Georg Brandl19564802006-05-10 17:13:20 +00001002 print >>self.stdout, """enable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +00001003Enables the breakpoints given as a space separated list of
1004bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001005
Tim Peters2344fae2001-01-15 00:50:52 +00001006 def help_disable(self):
Georg Brandl19564802006-05-10 17:13:20 +00001007 print >>self.stdout, """disable bpnumber [bpnumber ...]
Tim Peters2344fae2001-01-15 00:50:52 +00001008Disables the breakpoints given as a space separated list of
1009bp numbers."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001010
Tim Peters2344fae2001-01-15 00:50:52 +00001011 def help_ignore(self):
Georg Brandl19564802006-05-10 17:13:20 +00001012 print >>self.stdout, """ignore bpnumber count
Tim Peters2344fae2001-01-15 00:50:52 +00001013Sets the ignore count for the given breakpoint number. A breakpoint
1014becomes active when the ignore count is zero. When non-zero, the
1015count is decremented each time the breakpoint is reached and the
1016breakpoint is not disabled and any associated condition evaluates
1017to true."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001018
Tim Peters2344fae2001-01-15 00:50:52 +00001019 def help_condition(self):
Georg Brandl19564802006-05-10 17:13:20 +00001020 print >>self.stdout, """condition bpnumber str_condition
Tim Peters2344fae2001-01-15 00:50:52 +00001021str_condition is a string specifying an expression which
1022must evaluate to true before the breakpoint is honored.
1023If str_condition is absent, any existing condition is removed;
1024i.e., the breakpoint is made unconditional."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001025
Tim Peters2344fae2001-01-15 00:50:52 +00001026 def help_step(self):
1027 self.help_s()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001028
Tim Peters2344fae2001-01-15 00:50:52 +00001029 def help_s(self):
Georg Brandl19564802006-05-10 17:13:20 +00001030 print >>self.stdout, """s(tep)
Tim Peters2344fae2001-01-15 00:50:52 +00001031Execute the current line, stop at the first possible occasion
1032(either in a function that is called or in the current function)."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001033
Benjamin Peterson98353942008-05-11 14:13:25 +00001034 def help_until(self):
1035 self.help_unt()
1036
1037 def help_unt(self):
1038 print """unt(il)
1039Continue execution until the line with a number greater than the current
1040one is reached or until the current frame returns"""
1041
Tim Peters2344fae2001-01-15 00:50:52 +00001042 def help_next(self):
1043 self.help_n()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001044
Tim Peters2344fae2001-01-15 00:50:52 +00001045 def help_n(self):
Georg Brandl19564802006-05-10 17:13:20 +00001046 print >>self.stdout, """n(ext)
Tim Peters2344fae2001-01-15 00:50:52 +00001047Continue execution until the next line in the current function
1048is reached or it returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001049
Tim Peters2344fae2001-01-15 00:50:52 +00001050 def help_return(self):
1051 self.help_r()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001052
Tim Peters2344fae2001-01-15 00:50:52 +00001053 def help_r(self):
Georg Brandl19564802006-05-10 17:13:20 +00001054 print >>self.stdout, """r(eturn)
Tim Peters2344fae2001-01-15 00:50:52 +00001055Continue execution until the current function returns."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001056
Tim Peters2344fae2001-01-15 00:50:52 +00001057 def help_continue(self):
1058 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001059
Tim Peters2344fae2001-01-15 00:50:52 +00001060 def help_cont(self):
1061 self.help_c()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001062
Tim Peters2344fae2001-01-15 00:50:52 +00001063 def help_c(self):
Georg Brandl19564802006-05-10 17:13:20 +00001064 print >>self.stdout, """c(ont(inue))
Tim Peters2344fae2001-01-15 00:50:52 +00001065Continue execution, only stop when a breakpoint is encountered."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001066
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001067 def help_jump(self):
1068 self.help_j()
1069
1070 def help_j(self):
Georg Brandl19564802006-05-10 17:13:20 +00001071 print >>self.stdout, """j(ump) lineno
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001072Set the next line that will be executed."""
1073
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001074 def help_debug(self):
Georg Brandl19564802006-05-10 17:13:20 +00001075 print >>self.stdout, """debug code
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001076Enter a recursive debugger that steps through the code argument
1077(which is an arbitrary expression or statement to be executed
1078in the current environment)."""
1079
Tim Peters2344fae2001-01-15 00:50:52 +00001080 def help_list(self):
1081 self.help_l()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001082
Tim Peters2344fae2001-01-15 00:50:52 +00001083 def help_l(self):
Georg Brandl19564802006-05-10 17:13:20 +00001084 print >>self.stdout, """l(ist) [first [,last]]
Tim Peters2344fae2001-01-15 00:50:52 +00001085List source code for the current file.
1086Without arguments, list 11 lines around the current line
1087or continue the previous listing.
1088With one argument, list 11 lines starting at that line.
1089With two arguments, list the given range;
1090if the second argument is less than the first, it is a count."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001091
Tim Peters2344fae2001-01-15 00:50:52 +00001092 def help_args(self):
1093 self.help_a()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001094
Tim Peters2344fae2001-01-15 00:50:52 +00001095 def help_a(self):
Georg Brandl19564802006-05-10 17:13:20 +00001096 print >>self.stdout, """a(rgs)
Tim Peters2344fae2001-01-15 00:50:52 +00001097Print the arguments of the current function."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001098
Tim Peters2344fae2001-01-15 00:50:52 +00001099 def help_p(self):
Georg Brandl19564802006-05-10 17:13:20 +00001100 print >>self.stdout, """p expression
Tim Peters2344fae2001-01-15 00:50:52 +00001101Print the value of the expression."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001102
Barry Warsaw210bd202002-11-05 22:40:20 +00001103 def help_pp(self):
Georg Brandl19564802006-05-10 17:13:20 +00001104 print >>self.stdout, """pp expression
Barry Warsaw210bd202002-11-05 22:40:20 +00001105Pretty-print the value of the expression."""
1106
Tim Peters2344fae2001-01-15 00:50:52 +00001107 def help_exec(self):
Georg Brandl19564802006-05-10 17:13:20 +00001108 print >>self.stdout, """(!) statement
Tim Peters2344fae2001-01-15 00:50:52 +00001109Execute the (one-line) statement in the context of
1110the current stack frame.
1111The exclamation point can be omitted unless the first word
1112of the statement resembles a debugger command.
1113To assign to a global variable you must always prefix the
1114command with a 'global' command, e.g.:
1115(Pdb) global list_options; list_options = ['-l']
1116(Pdb)"""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001117
Georg Brandl8e84c652007-03-13 21:08:15 +00001118 def help_run(self):
1119 print """run [args...]
1120Restart the debugged python program. If a string is supplied, it is
1121splitted with "shlex" and the result is used as the new sys.argv.
1122History, breakpoints, actions and debugger options are preserved.
1123"restart" is an alias for "run"."""
1124
1125 help_restart = help_run
1126
Tim Peters2344fae2001-01-15 00:50:52 +00001127 def help_quit(self):
1128 self.help_q()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001129
Tim Peters2344fae2001-01-15 00:50:52 +00001130 def help_q(self):
Georg Brandl19564802006-05-10 17:13:20 +00001131 print >>self.stdout, """q(uit) or exit - Quit from the debugger.
Tim Peters2344fae2001-01-15 00:50:52 +00001132The program being executed is aborted."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001133
Guido van Rossumd1c08f32002-04-15 00:48:24 +00001134 help_exit = help_q
1135
Tim Peters2344fae2001-01-15 00:50:52 +00001136 def help_whatis(self):
Georg Brandl19564802006-05-10 17:13:20 +00001137 print >>self.stdout, """whatis arg
Tim Peters2344fae2001-01-15 00:50:52 +00001138Prints the type of the argument."""
Guido van Rossumb6775db1994-08-01 11:34:53 +00001139
Tim Peters2344fae2001-01-15 00:50:52 +00001140 def help_EOF(self):
Georg Brandl19564802006-05-10 17:13:20 +00001141 print >>self.stdout, """EOF
Tim Peters2344fae2001-01-15 00:50:52 +00001142Handles the receipt of EOF as a command."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001143
Tim Peters2344fae2001-01-15 00:50:52 +00001144 def help_alias(self):
Georg Brandl58152202009-05-05 09:06:02 +00001145 print >>self.stdout, """alias [name [command [parameter parameter ...]]]
Tim Peters2344fae2001-01-15 00:50:52 +00001146Creates an alias called 'name' the executes 'command'. The command
1147must *not* be enclosed in quotes. Replaceable parameters are
1148indicated by %1, %2, and so on, while %* is replaced by all the
1149parameters. If no command is given, the current alias for name
1150is shown. If no name is given, all aliases are listed.
Guido van Rossum2424f851998-09-11 22:50:09 +00001151
Tim Peters2344fae2001-01-15 00:50:52 +00001152Aliases may be nested and can contain anything that can be
1153legally typed at the pdb prompt. Note! You *can* override
1154internal pdb commands with aliases! Those internal commands
1155are then hidden until the alias is removed. Aliasing is recursively
1156applied to the first word of the command line; all other words
1157in the line are left alone.
Guido van Rossum2424f851998-09-11 22:50:09 +00001158
Tim Peters2344fae2001-01-15 00:50:52 +00001159Some useful aliases (especially when placed in the .pdbrc file) are:
Guido van Rossum2424f851998-09-11 22:50:09 +00001160
Tim Peters2344fae2001-01-15 00:50:52 +00001161#Print instance variables (usage "pi classInst")
1162alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
Guido van Rossum2424f851998-09-11 22:50:09 +00001163
Tim Peters2344fae2001-01-15 00:50:52 +00001164#Print instance variables in self
1165alias ps pi self
1166"""
Guido van Rossum2424f851998-09-11 22:50:09 +00001167
Tim Peters2344fae2001-01-15 00:50:52 +00001168 def help_unalias(self):
Georg Brandl19564802006-05-10 17:13:20 +00001169 print >>self.stdout, """unalias name
Tim Peters2344fae2001-01-15 00:50:52 +00001170Deletes the specified alias."""
Guido van Rossum2424f851998-09-11 22:50:09 +00001171
Martin v. Löwisbd30f522006-04-17 17:08:37 +00001172 def help_commands(self):
Georg Brandl19564802006-05-10 17:13:20 +00001173 print >>self.stdout, """commands [bpnumber]
Martin v. Löwisbd30f522006-04-17 17:08:37 +00001174(com) ...
1175(com) end
1176(Pdb)
1177
1178Specify a list of commands for breakpoint number bpnumber. The
1179commands themselves appear on the following lines. Type a line
1180containing just 'end' to terminate the commands.
1181
1182To remove all commands from a breakpoint, type commands and
1183follow it immediately with end; that is, give no commands.
1184
1185With no bpnumber argument, commands refers to the last
1186breakpoint set.
1187
1188You can use breakpoint commands to start your program up again.
1189Simply use the continue command, or step, or any other
1190command that resumes execution.
1191
1192Specifying any command resuming execution (currently continue,
1193step, next, return, jump, quit and their abbreviations) terminates
1194the command list (as if that command was immediately followed by end).
1195This is because any time you resume execution
Martin v. Löwisf62eee12006-04-17 17:37:09 +00001196(even with a simple next or step), you may encounter
Martin v. Löwisbd30f522006-04-17 17:08:37 +00001197another breakpoint--which could have its own command list, leading to
1198ambiguities about which list to execute.
1199
1200 If you use the 'silent' command in the command list, the
1201usual message about stopping at a breakpoint is not printed. This may
1202be desirable for breakpoints that are to print a specific message and
1203then continue. If none of the other commands print anything, you
1204see no sign that the breakpoint was reached.
1205"""
1206
Tim Peters2344fae2001-01-15 00:50:52 +00001207 def help_pdb(self):
1208 help()
Guido van Rossumb6775db1994-08-01 11:34:53 +00001209
Tim Peters2344fae2001-01-15 00:50:52 +00001210 def lookupmodule(self, filename):
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001211 """Helper function for break/clear parsing -- may be overridden.
1212
1213 lookupmodule() translates (possibly incomplete) file or module name
1214 into an absolute file name.
1215 """
1216 if os.path.isabs(filename) and os.path.exists(filename):
Tim Peterse718f612004-10-12 21:51:32 +00001217 return filename
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001218 f = os.path.join(sys.path[0], filename)
1219 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1220 return f
Tim Peters2344fae2001-01-15 00:50:52 +00001221 root, ext = os.path.splitext(filename)
1222 if ext == '':
1223 filename = filename + '.py'
1224 if os.path.isabs(filename):
1225 return filename
1226 for dirname in sys.path:
1227 while os.path.islink(dirname):
1228 dirname = os.readlink(dirname)
1229 fullname = os.path.join(dirname, filename)
1230 if os.path.exists(fullname):
1231 return fullname
1232 return None
Guido van Rossumb5699c71998-07-20 23:13:54 +00001233
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001234 def _runscript(self, filename):
Georg Brandlb6ae6aa2007-03-13 21:58:44 +00001235 # The script has to run in __main__ namespace (or imports from
1236 # __main__ will break).
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001237 #
Georg Brandlb6ae6aa2007-03-13 21:58:44 +00001238 # So we clear up the __main__ and set several special variables
1239 # (this gets rid of pdb's globals and cleans old variables on restarts).
1240 import __main__
1241 __main__.__dict__.clear()
1242 __main__.__dict__.update({"__name__" : "__main__",
1243 "__file__" : filename,
1244 "__builtins__": __builtins__,
1245 })
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001246
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001247 # When bdb sets tracing, a number of call and line events happens
1248 # BEFORE debugger even reaches user's code (and the exact sequence of
1249 # events depends on python version). So we take special measures to
1250 # avoid stopping before we reach the main script (see user_line and
1251 # user_call for details).
1252 self._wait_for_mainpyfile = 1
1253 self.mainpyfile = self.canonic(filename)
1254 self._user_requested_quit = 0
1255 statement = 'execfile( "%s")' % filename
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001256 self.run(statement)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001257
Guido van Rossum35771131992-09-08 11:59:04 +00001258# Simplified interface
1259
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001260def run(statement, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001261 Pdb().run(statement, globals, locals)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +00001262
1263def runeval(expression, globals=None, locals=None):
Tim Peters2344fae2001-01-15 00:50:52 +00001264 return Pdb().runeval(expression, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001265
1266def runctx(statement, globals, locals):
Tim Peters2344fae2001-01-15 00:50:52 +00001267 # B/W compatibility
1268 run(statement, globals, locals)
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001269
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +00001270def runcall(*args, **kwds):
1271 return Pdb().runcall(*args, **kwds)
Guido van Rossum4e160981992-09-02 20:43:20 +00001272
Guido van Rossumb6775db1994-08-01 11:34:53 +00001273def set_trace():
Johannes Gijsbers84a6c202004-11-07 11:35:30 +00001274 Pdb().set_trace(sys._getframe().f_back)
Guido van Rossum35771131992-09-08 11:59:04 +00001275
1276# Post-Mortem interface
1277
Facundo Batistac54aec12008-03-08 16:50:27 +00001278def post_mortem(t=None):
1279 # handling the default
1280 if t is None:
1281 # sys.exc_info() returns (type, value, traceback) if an exception is
1282 # being handled, otherwise it returns None
1283 t = sys.exc_info()[2]
1284 if t is None:
1285 raise ValueError("A valid traceback must be passed if no "
1286 "exception is being handled")
1287
Tim Peters2344fae2001-01-15 00:50:52 +00001288 p = Pdb()
1289 p.reset()
Benjamin Petersonc18574c2008-10-22 21:16:34 +00001290 p.interaction(None, t)
Guido van Rossum35771131992-09-08 11:59:04 +00001291
1292def pm():
Tim Peters2344fae2001-01-15 00:50:52 +00001293 post_mortem(sys.last_traceback)
Guido van Rossum35771131992-09-08 11:59:04 +00001294
1295
1296# Main program for testing
1297
Guido van Rossum23efba41992-01-27 16:58:47 +00001298TESTCMD = 'import x; x.main()'
Guido van Rossum6fe08b01992-01-16 13:50:21 +00001299
Guido van Rossum921c8241992-01-10 14:54:42 +00001300def test():
Tim Peters2344fae2001-01-15 00:50:52 +00001301 run(TESTCMD)
Guido van Rossume61fa0a1993-10-22 13:56:35 +00001302
1303# print help
1304def help():
Tim Peters2344fae2001-01-15 00:50:52 +00001305 for dirname in sys.path:
1306 fullname = os.path.join(dirname, 'pdb.doc')
1307 if os.path.exists(fullname):
1308 sts = os.system('${PAGER-more} '+fullname)
1309 if sts: print '*** Pager exit status:', sts
1310 break
1311 else:
1312 print 'Sorry, can\'t find the help file "pdb.doc"',
1313 print 'along the Python search path'
Guido van Rossumf17361d1996-07-30 16:28:13 +00001314
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001315def main():
Benjamin Peterson13be2cf2008-03-26 11:57:47 +00001316 if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
Tim Peters2344fae2001-01-15 00:50:52 +00001317 print "usage: pdb.py scriptfile [arg] ..."
1318 sys.exit(2)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001319
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001320 mainpyfile = sys.argv[1] # Get script filename
1321 if not os.path.exists(mainpyfile):
1322 print 'Error:', mainpyfile, 'does not exist'
Tim Peters2344fae2001-01-15 00:50:52 +00001323 sys.exit(1)
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001324
Tim Peters2344fae2001-01-15 00:50:52 +00001325 del sys.argv[0] # Hide "pdb.py" from argument list
Guido van Rossumec577d51996-09-10 17:39:34 +00001326
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001327 # Replace pdb's dir with script's dir in front of module search path.
1328 sys.path[0] = os.path.dirname(mainpyfile)
Guido van Rossumf17361d1996-07-30 16:28:13 +00001329
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001330 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1331 # modified by the script being debugged. It's a bad idea when it was
Georg Brandl58152202009-05-05 09:06:02 +00001332 # changed by the user from the command line. There is a "restart" command
1333 # which allows explicit specification of command line arguments.
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001334 pdb = Pdb()
1335 while 1:
1336 try:
1337 pdb._runscript(mainpyfile)
1338 if pdb._user_requested_quit:
1339 break
Tim Peterse718f612004-10-12 21:51:32 +00001340 print "The program finished and will be restarted"
Georg Brandl8e84c652007-03-13 21:08:15 +00001341 except Restart:
1342 print "Restarting", mainpyfile, "with arguments:"
1343 print "\t" + " ".join(sys.argv[1:])
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001344 except SystemExit:
1345 # In most cases SystemExit does not warrant a post-mortem session.
1346 print "The program exited via sys.exit(). Exit status: ",
1347 print sys.exc_info()[1]
1348 except:
1349 traceback.print_exc()
1350 print "Uncaught exception. Entering post mortem debugging"
1351 print "Running 'cont' or 'step' will restart the program"
1352 t = sys.exc_info()[2]
Benjamin Petersonc18574c2008-10-22 21:16:34 +00001353 pdb.interaction(None, t)
Georg Brandl58152202009-05-05 09:06:02 +00001354 print "Post mortem debugger finished. The " + mainpyfile + \
1355 " will be restarted"
Johannes Gijsbers25b38c82004-10-12 18:12:09 +00001356
1357
1358# When invoked as main program, invoke the debugger on a script
Georg Brandlb6ae6aa2007-03-13 21:58:44 +00001359if __name__ == '__main__':
1360 import pdb
1361 pdb.main()