Fixed a wrong apostrophe
[python.git] / Lib / pdb.py
blobeae62960ce92184a96074ec52c5320cf20aab6a6
1 #! /usr/bin/env python
3 """A Python debugger."""
5 # (See pdb.doc for documentation.)
7 import sys
8 import linecache
9 import cmd
10 import bdb
11 from repr import Repr
12 import os
13 import re
14 import pprint
15 import traceback
18 class Restart(Exception):
19 """Causes a debugger to be restarted for the debugged python program."""
20 pass
22 # 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
28 __all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
29 "post_mortem", "help"]
31 def find_function(funcname, filename):
32 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname))
33 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
52 # 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% '".
56 # line_prefix = ': ' # Use this to get the old situation back
57 line_prefix = '\n-> ' # Probably a better default
59 class Pdb(bdb.Bdb, cmd.Cmd):
61 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None):
62 bdb.Bdb.__init__(self, skip=skip)
63 cmd.Cmd.__init__(self, completekey, stdin, stdout)
64 if stdout:
65 self.use_rawinput = 0
66 self.prompt = '(Pdb) '
67 self.aliases = {}
68 self.mainpyfile = ''
69 self._wait_for_mainpyfile = 0
70 # Try to load readline if it exists
71 try:
72 import readline
73 except ImportError:
74 pass
76 # Read $HOME/.pdbrc and ./.pdbrc
77 self.rcLines = []
78 if 'HOME' in os.environ:
79 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()
97 self.commands = {} # associates a command list to breakpoint numbers
98 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
107 def reset(self):
108 bdb.Bdb.reset(self)
109 self.forget()
111 def forget(self):
112 self.lineno = None
113 self.stack = []
114 self.curindex = 0
115 self.curframe = None
117 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]
121 # 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
125 self.execRcLines()
127 # 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]
136 if len(line) > 0 and line[0] != '#':
137 self.onecmd(line)
139 # Override Bdb methods
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."""
144 if self._wait_for_mainpyfile:
145 return
146 if self.stop_here(frame):
147 print >>self.stdout, '--Call--'
148 self.interaction(frame, None)
150 def user_line(self, frame):
151 """This function is called when we stop or break at this line."""
152 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
157 if self.bp_commands(frame):
158 self.interaction(frame, None)
160 def bp_commands(self,frame):
161 """Call every command that was set for the current active breakpoint
162 (if there is one).
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:
169 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()
181 return
182 return 1
184 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
187 print >>self.stdout, '--Return--'
188 self.interaction(frame, None)
190 def user_exception(self, frame, exc_info):
191 exc_type, exc_value, exc_traceback = exc_info
192 """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__
198 print >>self.stdout, exc_type_name + ':', _saferepr(exc_value)
199 self.interaction(frame, exc_traceback)
201 # General interaction function
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()
209 def displayhook(self, obj):
210 """Custom displayhook for the exec in default(), which prevents
211 assignment of the _ variable in the builtins.
213 print repr(obj)
215 def default(self, line):
216 if line[:1] == '!': line = line[1:]
217 locals = self.curframe_locals
218 globals = self.curframe.f_globals
219 try:
220 code = compile(line + '\n', '<stdin>', 'single')
221 save_stdout = sys.stdout
222 save_stdin = sys.stdin
223 save_displayhook = sys.displayhook
224 try:
225 sys.stdin = self.stdin
226 sys.stdout = self.stdout
227 sys.displayhook = self.displayhook
228 exec code in globals, locals
229 finally:
230 sys.stdout = save_stdout
231 sys.stdin = save_stdin
232 sys.displayhook = save_displayhook
233 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__
238 print >>self.stdout, '***', exc_type_name + ':', v
240 def precmd(self, line):
241 """Handle alias expansion and ';;' separator."""
242 if not line.strip():
243 return line
244 args = line.split()
245 while args[0] in self.aliases:
246 line = self.aliases[args[0]]
247 ii = 1
248 for tmpArg in args[1:]:
249 line = line.replace("%" + str(ii),
250 tmpArg)
251 ii = ii + 1
252 line = line.replace("%*", ' '.join(args[1:]))
253 args = line.split()
254 # split into ';;' separated commands
255 # unless it's an alias command
256 if args[0] != 'alias':
257 marker = line.find(';;')
258 if marker >= 0:
259 # queue up everything after marker
260 next = line[marker+2:].lstrip()
261 self.cmdqueue.append(next)
262 line = line[:marker].rstrip()
263 return line
265 def onecmd(self, line):
266 """Interpret the argument as though it had been typed in response
267 to the prompt.
269 Checks whether this line is typed at the normal prompt or in
270 a breakpoint command list definition.
272 if not self.commands_defining:
273 return cmd.Cmd.onecmd(self, line)
274 else:
275 return self.handle_command_def(line)
277 def handle_command_def(self,line):
278 """ 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
296 # one of the resuming commands
297 if func.func_name in self.commands_resuming:
298 self.commands_doprompt[self.commands_bnum] = False
299 self.cmdqueue = []
300 return 1
301 return
303 # 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
307 do_h = cmd.Cmd.do_help
309 def do_commands(self, arg):
310 """Defines a list of commands associated to a breakpoint.
312 Those commands will be executed whenever the breakpoint causes
313 the program to stop execution."""
314 if not arg:
315 bnum = len(bdb.Breakpoint.bpbynumber)-1
316 else:
317 try:
318 bnum = int(arg)
319 except:
320 print >>self.stdout, "Usage : commands [bnum]\n ..." \
321 "\n end"
322 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
334 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
338 print >>self.stdout, "Num Type Disp Enb Where"
339 for bp in bdb.Breakpoint.bpbynumber:
340 if bp:
341 bp.bpprint(self.stdout)
342 return
343 # parse arguments; comma has lowest precedence
344 # and cannot occur in filename
345 filename = None
346 lineno = None
347 cond = None
348 comma = arg.find(',')
349 if comma > 0:
350 # parse stuff after comma: "condition"
351 cond = arg[comma+1:].lstrip()
352 arg = arg[:comma].rstrip()
353 # parse stuff before comma: [filename:]lineno | function
354 colon = arg.rfind(':')
355 funcname = None
356 if colon >= 0:
357 filename = arg[:colon].rstrip()
358 f = self.lookupmodule(filename)
359 if not f:
360 print >>self.stdout, '*** ', repr(filename),
361 print >>self.stdout, 'not found from sys.path'
362 return
363 else:
364 filename = f
365 arg = arg[colon+1:].lstrip()
366 try:
367 lineno = int(arg)
368 except ValueError, msg:
369 print >>self.stdout, '*** Bad lineno:', arg
370 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,
379 self.curframe_locals)
380 except:
381 func = arg
382 try:
383 if hasattr(func, 'im_func'):
384 func = func.im_func
385 code = func.func_code
386 #use co_name to identify the bkpt (function names
387 #could be aliased, but co_name is invariant)
388 funcname = code.co_name
389 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:
395 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.'
399 return
400 funcname = ok # ok contains a function name
401 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
408 err = self.set_break(filename, line, temporary, cond, funcname)
409 if err: print >>self.stdout, '***', err
410 else:
411 bp = self.get_breaks(filename, line)[-1]
412 print >>self.stdout, "Breakpoint %d at %s:%d" % (bp.number,
413 bp.file,
414 bp.line)
416 # To be overridden in derived debuggers
417 def defaultFile(self):
418 """Produce a reasonable default."""
419 filename = self.curframe.f_code.co_filename
420 if filename == '<string>' and self.mainpyfile:
421 filename = self.mainpyfile
422 return filename
424 do_b = do_break
426 def do_tbreak(self, arg):
427 self.do_break(arg, 1)
429 def lineinfo(self, identifier):
430 failed = (None, None, None)
431 # Input is identifier, may be in single quotes
432 idstring = identifier.split("'")
433 if len(idstring) == 1:
434 # not in single quotes
435 id = idstring[0].strip()
436 elif len(idstring) == 3:
437 # quoted
438 id = idstring[1].strip()
439 else:
440 return failed
441 if id == '': return failed
442 parts = id.split('.')
443 # 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
462 def checkline(self, filename, lineno):
463 """Check whether specified line seems to be executable.
465 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
466 line or EOF). Warning: testing is not comprehensive.
468 line = linecache.getline(filename, lineno, self.curframe.f_globals)
469 if not line:
470 print >>self.stdout, 'End of file'
471 return 0
472 line = line.strip()
473 # Don't allow setting breakpoint at a blank line
474 if (not line or (line[0] == '#') or
475 (line[:3] == '"""') or line[:3] == "'''"):
476 print >>self.stdout, '*** Blank or comment'
477 return 0
478 return lineno
480 def do_enable(self, arg):
481 args = arg.split()
482 for i in args:
483 try:
484 i = int(i)
485 except ValueError:
486 print >>self.stdout, 'Breakpoint index %r is not a number' % i
487 continue
489 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
490 print >>self.stdout, 'No breakpoint numbered', i
491 continue
493 bp = bdb.Breakpoint.bpbynumber[i]
494 if bp:
495 bp.enable()
497 def do_disable(self, arg):
498 args = arg.split()
499 for i in args:
500 try:
501 i = int(i)
502 except ValueError:
503 print >>self.stdout, 'Breakpoint index %r is not a number' % i
504 continue
506 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
507 print >>self.stdout, 'No breakpoint numbered', i
508 continue
510 bp = bdb.Breakpoint.bpbynumber[i]
511 if bp:
512 bp.disable()
514 def do_condition(self, arg):
515 # arg is breakpoint number and condition
516 args = arg.split(' ', 1)
517 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]
523 return
524 try:
525 cond = args[1]
526 except:
527 cond = None
528 try:
529 bp = bdb.Breakpoint.bpbynumber[bpnum]
530 except IndexError:
531 print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
532 return
533 if bp:
534 bp.cond = cond
535 if not cond:
536 print >>self.stdout, 'Breakpoint', bpnum,
537 print >>self.stdout, 'is now unconditional.'
539 def do_ignore(self,arg):
540 """arg is bp number followed by ignore count."""
541 args = arg.split()
542 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]
548 return
549 try:
550 count = int(args[1].strip())
551 except:
552 count = 0
553 try:
554 bp = bdb.Breakpoint.bpbynumber[bpnum]
555 except IndexError:
556 print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
557 return
558 if bp:
559 bp.ignore = count
560 if count > 0:
561 reply = 'Will ignore next '
562 if count > 1:
563 reply = reply + '%d crossings' % count
564 else:
565 reply = reply + '1 crossing'
566 print >>self.stdout, reply + ' of breakpoint %d.' % bpnum
567 else:
568 print >>self.stdout, 'Will stop next time breakpoint',
569 print >>self.stdout, bpnum, 'is reached.'
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'
581 reply = reply.strip().lower()
582 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"
587 i = arg.rfind(':')
588 filename = arg[:i]
589 arg = arg[i+1:]
590 try:
591 lineno = int(arg)
592 except ValueError:
593 err = "Invalid line number (%s)" % arg
594 else:
595 err = self.clear_break(filename, lineno)
596 if err: print >>self.stdout, '***', err
597 return
598 numberlist = arg.split()
599 for i in numberlist:
600 try:
601 i = int(i)
602 except ValueError:
603 print >>self.stdout, 'Breakpoint index %r is not a number' % i
604 continue
606 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
607 print >>self.stdout, 'No breakpoint numbered', i
608 continue
609 err = self.clear_bpbynumber(i)
610 if err:
611 print >>self.stdout, '***', err
612 else:
613 print >>self.stdout, 'Deleted breakpoint', i
614 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
616 def do_where(self, arg):
617 self.print_stack_trace()
618 do_w = do_where
619 do_bt = do_where
621 def do_up(self, arg):
622 if self.curindex == 0:
623 print >>self.stdout, '*** Oldest frame'
624 else:
625 self.curindex = self.curindex - 1
626 self.curframe = self.stack[self.curindex][0]
627 self.curframe_locals = self.curframe.f_locals
628 self.print_stack_entry(self.stack[self.curindex])
629 self.lineno = None
630 do_u = do_up
632 def do_down(self, arg):
633 if self.curindex + 1 == len(self.stack):
634 print >>self.stdout, '*** Newest frame'
635 else:
636 self.curindex = self.curindex + 1
637 self.curframe = self.stack[self.curindex][0]
638 self.curframe_locals = self.curframe.f_locals
639 self.print_stack_entry(self.stack[self.curindex])
640 self.lineno = None
641 do_d = do_down
643 def do_until(self, arg):
644 self.set_until(self.curframe)
645 return 1
646 do_unt = do_until
648 def do_step(self, arg):
649 self.set_step()
650 return 1
651 do_s = do_step
653 def do_next(self, arg):
654 self.set_next(self.curframe)
655 return 1
656 do_n = do_next
658 def do_run(self, arg):
659 """Restart program by raising an exception to be caught in the main
660 debugger loop. If arguments were given, set them in sys.argv."""
661 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
668 do_restart = do_run
670 def do_return(self, arg):
671 self.set_return(self.curframe)
672 return 1
673 do_r = do_return
675 def do_continue(self, arg):
676 self.set_continue()
677 return 1
678 do_c = do_cont = do_continue
680 def do_jump(self, arg):
681 if self.curindex + 1 != len(self.stack):
682 print >>self.stdout, "*** You can only jump within the bottom frame"
683 return
684 try:
685 arg = int(arg)
686 except ValueError:
687 print >>self.stdout, "*** The 'jump' command requires a line number."
688 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:
696 print >>self.stdout, '*** Jump failed:', e
697 do_j = do_jump
699 def do_debug(self, arg):
700 sys.settrace(None)
701 globals = self.curframe.f_globals
702 locals = self.curframe_locals
703 p = Pdb(self.completekey, self.stdin, self.stdout)
704 p.prompt = "(%s) " % self.prompt.strip()
705 print >>self.stdout, "ENTERING RECURSIVE DEBUGGER"
706 sys.call_tracing(p.run, (arg, globals, locals))
707 print >>self.stdout, "LEAVING RECURSIVE DEBUGGER"
708 sys.settrace(self.trace_dispatch)
709 self.lastcmd = p.lastcmd
711 def do_quit(self, arg):
712 self._user_requested_quit = 1
713 self.set_quit()
714 return 1
716 do_q = do_quit
717 do_exit = do_quit
719 def do_EOF(self, arg):
720 print >>self.stdout
721 self._user_requested_quit = 1
722 self.set_quit()
723 return 1
725 def do_args(self, arg):
726 co = self.curframe.f_code
727 dict = self.curframe_locals
728 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]
733 print >>self.stdout, name, '=',
734 if name in dict: print >>self.stdout, dict[name]
735 else: print >>self.stdout, "*** undefined ***"
736 do_a = do_args
738 def do_retval(self, arg):
739 if '__return__' in self.curframe_locals:
740 print >>self.stdout, self.curframe_locals['__return__']
741 else:
742 print >>self.stdout, '*** Not yet returned!'
743 do_rv = do_retval
745 def _getval(self, arg):
746 try:
747 return eval(arg, self.curframe.f_globals,
748 self.curframe_locals)
749 except:
750 t, v = sys.exc_info()[:2]
751 if isinstance(t, str):
752 exc_type_name = t
753 else: exc_type_name = t.__name__
754 print >>self.stdout, '***', exc_type_name + ':', repr(v)
755 raise
757 def do_p(self, arg):
758 try:
759 print >>self.stdout, repr(self._getval(arg))
760 except:
761 pass
763 def do_pp(self, arg):
764 try:
765 pprint.pprint(self._getval(arg), self.stdout)
766 except:
767 pass
769 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:
785 print >>self.stdout, '*** Error in argument:', repr(arg)
786 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):
797 line = linecache.getline(filename, lineno,
798 self.curframe.f_globals)
799 if not line:
800 print >>self.stdout, '[EOF]'
801 break
802 else:
803 s = repr(lineno).rjust(3)
804 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 + '->'
809 print >>self.stdout, s + '\t' + line,
810 self.lineno = lineno
811 except KeyboardInterrupt:
812 pass
813 do_l = do_list
815 def do_whatis(self, arg):
816 try:
817 value = eval(arg, self.curframe.f_globals,
818 self.curframe_locals)
819 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__
824 print >>self.stdout, '***', exc_type_name + ':', repr(v)
825 return
826 code = None
827 # Is it a function?
828 try: code = value.func_code
829 except: pass
830 if code:
831 print >>self.stdout, 'Function', code.co_name
832 return
833 # Is it an instance method?
834 try: code = value.im_func.func_code
835 except: pass
836 if code:
837 print >>self.stdout, 'Method', code.co_name
838 return
839 # None of the above...
840 print >>self.stdout, type(value)
842 def do_alias(self, arg):
843 args = arg.split()
844 if len(args) == 0:
845 keys = self.aliases.keys()
846 keys.sort()
847 for alias in keys:
848 print >>self.stdout, "%s = %s" % (alias, self.aliases[alias])
849 return
850 if args[0] in self.aliases and len(args) == 1:
851 print >>self.stdout, "%s = %s" % (args[0], self.aliases[args[0]])
852 else:
853 self.aliases[args[0]] = ' '.join(args[1:])
855 def do_unalias(self, arg):
856 args = arg.split()
857 if len(args) == 0: return
858 if args[0] in self.aliases:
859 del self.aliases[args[0]]
861 #list of all the commands making the program resume execution.
862 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
863 'do_quit', 'do_jump']
865 # 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).
873 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
880 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
881 frame, lineno = frame_lineno
882 if frame is self.curframe:
883 print >>self.stdout, '>',
884 else:
885 print >>self.stdout, ' ',
886 print >>self.stdout, self.format_stack_entry(frame_lineno,
887 prompt_prefix)
890 # Help methods (derived from pdb.doc)
892 def help_help(self):
893 self.help_h()
895 def help_h(self):
896 print >>self.stdout, """h(elp)
897 Without argument, print the list of available commands.
898 With 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"""
902 def help_where(self):
903 self.help_w()
905 def help_w(self):
906 print >>self.stdout, """w(here)
907 Print a stack trace, with the most recent frame at the bottom.
908 An arrow indicates the "current frame", which determines the
909 context of most commands. 'bt' is an alias for this command."""
911 help_bt = help_w
913 def help_down(self):
914 self.help_d()
916 def help_d(self):
917 print >>self.stdout, """d(own)
918 Move the current frame one level down in the stack trace
919 (to a newer frame)."""
921 def help_up(self):
922 self.help_u()
924 def help_u(self):
925 print >>self.stdout, """u(p)
926 Move the current frame one level up in the stack trace
927 (to an older frame)."""
929 def help_break(self):
930 self.help_b()
932 def help_b(self):
933 print >>self.stdout, """b(reak) ([file:]lineno | function) [, condition]
934 With a line number argument, set a break there in the current
935 file. With a function name, set a break at first executable line
936 of that function. Without argument, list all breaks. If a second
937 argument is present, it is a string specifying an expression
938 which must evaluate to true before the breakpoint is honored.
940 The line number may be prefixed with a filename and a colon,
941 to specify a breakpoint in another file (probably one that
942 hasn't been loaded yet). The file is searched for on sys.path;
943 the .py suffix may be omitted."""
945 def help_clear(self):
946 self.help_cl()
948 def help_cl(self):
949 print >>self.stdout, "cl(ear) filename:lineno"
950 print >>self.stdout, """cl(ear) [bpnumber [bpnumber...]]
951 With a space separated list of breakpoint numbers, clear
952 those breakpoints. Without argument, clear all breaks (but
953 first ask confirmation). With a filename:lineno argument,
954 clear all breaks at that line in that file.
956 Note that the argument is different from previous versions of
957 the debugger (in python distributions 1.5.1 and before) where
958 a linenumber was used instead of either filename:lineno or
959 breakpoint numbers."""
961 def help_tbreak(self):
962 print >>self.stdout, """tbreak same arguments as break, but breakpoint
963 is removed when first hit."""
965 def help_enable(self):
966 print >>self.stdout, """enable bpnumber [bpnumber ...]
967 Enables the breakpoints given as a space separated list of
968 bp numbers."""
970 def help_disable(self):
971 print >>self.stdout, """disable bpnumber [bpnumber ...]
972 Disables the breakpoints given as a space separated list of
973 bp numbers."""
975 def help_ignore(self):
976 print >>self.stdout, """ignore bpnumber count
977 Sets the ignore count for the given breakpoint number. A breakpoint
978 becomes active when the ignore count is zero. When non-zero, the
979 count is decremented each time the breakpoint is reached and the
980 breakpoint is not disabled and any associated condition evaluates
981 to true."""
983 def help_condition(self):
984 print >>self.stdout, """condition bpnumber str_condition
985 str_condition is a string specifying an expression which
986 must evaluate to true before the breakpoint is honored.
987 If str_condition is absent, any existing condition is removed;
988 i.e., the breakpoint is made unconditional."""
990 def help_step(self):
991 self.help_s()
993 def help_s(self):
994 print >>self.stdout, """s(tep)
995 Execute the current line, stop at the first possible occasion
996 (either in a function that is called or in the current function)."""
998 def help_until(self):
999 self.help_unt()
1001 def help_unt(self):
1002 print """unt(il)
1003 Continue execution until the line with a number greater than the current
1004 one is reached or until the current frame returns"""
1006 def help_next(self):
1007 self.help_n()
1009 def help_n(self):
1010 print >>self.stdout, """n(ext)
1011 Continue execution until the next line in the current function
1012 is reached or it returns."""
1014 def help_return(self):
1015 self.help_r()
1017 def help_r(self):
1018 print >>self.stdout, """r(eturn)
1019 Continue execution until the current function returns."""
1021 def help_continue(self):
1022 self.help_c()
1024 def help_cont(self):
1025 self.help_c()
1027 def help_c(self):
1028 print >>self.stdout, """c(ont(inue))
1029 Continue execution, only stop when a breakpoint is encountered."""
1031 def help_jump(self):
1032 self.help_j()
1034 def help_j(self):
1035 print >>self.stdout, """j(ump) lineno
1036 Set the next line that will be executed."""
1038 def help_debug(self):
1039 print >>self.stdout, """debug code
1040 Enter a recursive debugger that steps through the code argument
1041 (which is an arbitrary expression or statement to be executed
1042 in the current environment)."""
1044 def help_list(self):
1045 self.help_l()
1047 def help_l(self):
1048 print >>self.stdout, """l(ist) [first [,last]]
1049 List source code for the current file.
1050 Without arguments, list 11 lines around the current line
1051 or continue the previous listing.
1052 With one argument, list 11 lines starting at that line.
1053 With two arguments, list the given range;
1054 if the second argument is less than the first, it is a count."""
1056 def help_args(self):
1057 self.help_a()
1059 def help_a(self):
1060 print >>self.stdout, """a(rgs)
1061 Print the arguments of the current function."""
1063 def help_p(self):
1064 print >>self.stdout, """p expression
1065 Print the value of the expression."""
1067 def help_pp(self):
1068 print >>self.stdout, """pp expression
1069 Pretty-print the value of the expression."""
1071 def help_exec(self):
1072 print >>self.stdout, """(!) statement
1073 Execute the (one-line) statement in the context of
1074 the current stack frame.
1075 The exclamation point can be omitted unless the first word
1076 of the statement resembles a debugger command.
1077 To assign to a global variable you must always prefix the
1078 command with a 'global' command, e.g.:
1079 (Pdb) global list_options; list_options = ['-l']
1080 (Pdb)"""
1082 def help_run(self):
1083 print """run [args...]
1084 Restart the debugged python program. If a string is supplied, it is
1085 splitted with "shlex" and the result is used as the new sys.argv.
1086 History, breakpoints, actions and debugger options are preserved.
1087 "restart" is an alias for "run"."""
1089 help_restart = help_run
1091 def help_quit(self):
1092 self.help_q()
1094 def help_q(self):
1095 print >>self.stdout, """q(uit) or exit - Quit from the debugger.
1096 The program being executed is aborted."""
1098 help_exit = help_q
1100 def help_whatis(self):
1101 print >>self.stdout, """whatis arg
1102 Prints the type of the argument."""
1104 def help_EOF(self):
1105 print >>self.stdout, """EOF
1106 Handles the receipt of EOF as a command."""
1108 def help_alias(self):
1109 print >>self.stdout, """alias [name [command [parameter parameter ...]]]
1110 Creates an alias called 'name' the executes 'command'. The command
1111 must *not* be enclosed in quotes. Replaceable parameters are
1112 indicated by %1, %2, and so on, while %* is replaced by all the
1113 parameters. If no command is given, the current alias for name
1114 is shown. If no name is given, all aliases are listed.
1116 Aliases may be nested and can contain anything that can be
1117 legally typed at the pdb prompt. Note! You *can* override
1118 internal pdb commands with aliases! Those internal commands
1119 are then hidden until the alias is removed. Aliasing is recursively
1120 applied to the first word of the command line; all other words
1121 in the line are left alone.
1123 Some useful aliases (especially when placed in the .pdbrc file) are:
1125 #Print instance variables (usage "pi classInst")
1126 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
1128 #Print instance variables in self
1129 alias ps pi self
1132 def help_unalias(self):
1133 print >>self.stdout, """unalias name
1134 Deletes the specified alias."""
1136 def help_commands(self):
1137 print >>self.stdout, """commands [bpnumber]
1138 (com) ...
1139 (com) end
1140 (Pdb)
1142 Specify a list of commands for breakpoint number bpnumber. The
1143 commands themselves appear on the following lines. Type a line
1144 containing just 'end' to terminate the commands.
1146 To remove all commands from a breakpoint, type commands and
1147 follow it immediately with end; that is, give no commands.
1149 With no bpnumber argument, commands refers to the last
1150 breakpoint set.
1152 You can use breakpoint commands to start your program up again.
1153 Simply use the continue command, or step, or any other
1154 command that resumes execution.
1156 Specifying any command resuming execution (currently continue,
1157 step, next, return, jump, quit and their abbreviations) terminates
1158 the command list (as if that command was immediately followed by end).
1159 This is because any time you resume execution
1160 (even with a simple next or step), you may encounter
1161 another breakpoint--which could have its own command list, leading to
1162 ambiguities about which list to execute.
1164 If you use the 'silent' command in the command list, the
1165 usual message about stopping at a breakpoint is not printed. This may
1166 be desirable for breakpoints that are to print a specific message and
1167 then continue. If none of the other commands print anything, you
1168 see no sign that the breakpoint was reached.
1171 def help_pdb(self):
1172 help()
1174 def lookupmodule(self, filename):
1175 """Helper function for break/clear parsing -- may be overridden.
1177 lookupmodule() translates (possibly incomplete) file or module name
1178 into an absolute file name.
1180 if os.path.isabs(filename) and os.path.exists(filename):
1181 return filename
1182 f = os.path.join(sys.path[0], filename)
1183 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1184 return f
1185 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
1198 def _runscript(self, filename):
1199 # The script has to run in __main__ namespace (or imports from
1200 # __main__ will break).
1202 # 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__,
1211 # 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
1220 self.run(statement)
1222 # Simplified interface
1224 def run(statement, globals=None, locals=None):
1225 Pdb().run(statement, globals, locals)
1227 def runeval(expression, globals=None, locals=None):
1228 return Pdb().runeval(expression, globals, locals)
1230 def runctx(statement, globals, locals):
1231 # B/W compatibility
1232 run(statement, globals, locals)
1234 def runcall(*args, **kwds):
1235 return Pdb().runcall(*args, **kwds)
1237 def set_trace():
1238 Pdb().set_trace(sys._getframe().f_back)
1240 # Post-Mortem interface
1242 def 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")
1252 p = Pdb()
1253 p.reset()
1254 p.interaction(None, t)
1256 def pm():
1257 post_mortem(sys.last_traceback)
1260 # Main program for testing
1262 TESTCMD = 'import x; x.main()'
1264 def test():
1265 run(TESTCMD)
1267 # print help
1268 def help():
1269 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'
1279 def main():
1280 if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
1281 print "usage: pdb.py scriptfile [arg] ..."
1282 sys.exit(2)
1284 mainpyfile = sys.argv[1] # Get script filename
1285 if not os.path.exists(mainpyfile):
1286 print 'Error:', mainpyfile, 'does not exist'
1287 sys.exit(1)
1289 del sys.argv[0] # Hide "pdb.py" from argument list
1291 # Replace pdb's dir with script's dir in front of module search path.
1292 sys.path[0] = os.path.dirname(mainpyfile)
1294 # 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
1296 # changed by the user from the command line. There is a "restart" command
1297 # which allows explicit specification of command line arguments.
1298 pdb = Pdb()
1299 while 1:
1300 try:
1301 pdb._runscript(mainpyfile)
1302 if pdb._user_requested_quit:
1303 break
1304 print "The program finished and will be restarted"
1305 except Restart:
1306 print "Restarting", mainpyfile, "with arguments:"
1307 print "\t" + " ".join(sys.argv[1:])
1308 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]
1317 pdb.interaction(None, t)
1318 print "Post mortem debugger finished. The " + mainpyfile + \
1319 " will be restarted"
1322 # When invoked as main program, invoke the debugger on a script
1323 if __name__ == '__main__':
1324 import pdb
1325 pdb.main()