Results of a rewrite pass
[python/dscho.git] / Lib / pdb.py
blobfffd0ad3b8ff6fd660ebdef54d75e0eb8d0f8c50
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
16 # Create a custom safe Repr instance and increase its maxstring.
17 # The default of 30 truncates error messages too easily.
18 _repr = Repr()
19 _repr.maxstring = 200
20 _saferepr = _repr.repr
22 __all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
23 "post_mortem", "help"]
25 def find_function(funcname, filename):
26 cre = re.compile(r'def\s+%s\s*[(]' % funcname)
27 try:
28 fp = open(filename)
29 except IOError:
30 return None
31 # consumer of this info expects the first line to be 1
32 lineno = 1
33 answer = None
34 while 1:
35 line = fp.readline()
36 if line == '':
37 break
38 if cre.match(line):
39 answer = funcname, filename, lineno
40 break
41 lineno = lineno + 1
42 fp.close()
43 return answer
46 # Interaction prompt line will separate file and call info from code
47 # text using value of line_prefix string. A newline and arrow may
48 # be to your liking. You can set it once pdb is imported using the
49 # command "pdb.line_prefix = '\n% '".
50 # line_prefix = ': ' # Use this to get the old situation back
51 line_prefix = '\n-> ' # Probably a better default
53 class Pdb(bdb.Bdb, cmd.Cmd):
55 def __init__(self):
56 bdb.Bdb.__init__(self)
57 cmd.Cmd.__init__(self)
58 self.prompt = '(Pdb) '
59 self.aliases = {}
60 # Try to load readline if it exists
61 try:
62 import readline
63 except ImportError:
64 pass
66 # Read $HOME/.pdbrc and ./.pdbrc
67 self.rcLines = []
68 if 'HOME' in os.environ:
69 envHome = os.environ['HOME']
70 try:
71 rcFile = open(os.path.join(envHome, ".pdbrc"))
72 except IOError:
73 pass
74 else:
75 for line in rcFile.readlines():
76 self.rcLines.append(line)
77 rcFile.close()
78 try:
79 rcFile = open(".pdbrc")
80 except IOError:
81 pass
82 else:
83 for line in rcFile.readlines():
84 self.rcLines.append(line)
85 rcFile.close()
87 def reset(self):
88 bdb.Bdb.reset(self)
89 self.forget()
91 def forget(self):
92 self.lineno = None
93 self.stack = []
94 self.curindex = 0
95 self.curframe = None
97 def setup(self, f, t):
98 self.forget()
99 self.stack, self.curindex = self.get_stack(f, t)
100 self.curframe = self.stack[self.curindex][0]
101 self.execRcLines()
103 # Can be executed earlier than 'setup' if desired
104 def execRcLines(self):
105 if self.rcLines:
106 # Make local copy because of recursion
107 rcLines = self.rcLines
108 # executed only once
109 self.rcLines = []
110 for line in rcLines:
111 line = line[:-1]
112 if len(line) > 0 and line[0] != '#':
113 self.onecmd(line)
115 # Override Bdb methods
117 def user_call(self, frame, argument_list):
118 """This method is called when there is the remote possibility
119 that we ever need to stop in this function."""
120 print '--Call--'
121 self.interaction(frame, None)
123 def user_line(self, frame):
124 """This function is called when we stop or break at this line."""
125 self.interaction(frame, None)
127 def user_return(self, frame, return_value):
128 """This function is called when a return trap is set here."""
129 frame.f_locals['__return__'] = return_value
130 print '--Return--'
131 self.interaction(frame, None)
133 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
134 """This function is called if an exception occurs,
135 but only if we are to stop at or just below this level."""
136 frame.f_locals['__exception__'] = exc_type, exc_value
137 if type(exc_type) == type(''):
138 exc_type_name = exc_type
139 else: exc_type_name = exc_type.__name__
140 print exc_type_name + ':', _saferepr(exc_value)
141 self.interaction(frame, exc_traceback)
143 # General interaction function
145 def interaction(self, frame, traceback):
146 self.setup(frame, traceback)
147 self.print_stack_entry(self.stack[self.curindex])
148 self.cmdloop()
149 self.forget()
151 def default(self, line):
152 if line[:1] == '!': line = line[1:]
153 locals = self.curframe.f_locals
154 globals = self.curframe.f_globals
155 try:
156 code = compile(line + '\n', '<stdin>', 'single')
157 exec code in globals, locals
158 except:
159 t, v = sys.exc_info()[:2]
160 if type(t) == type(''):
161 exc_type_name = t
162 else: exc_type_name = t.__name__
163 print '***', exc_type_name + ':', v
165 def precmd(self, line):
166 """Handle alias expansion and ';;' separator."""
167 if not line.strip():
168 return line
169 args = line.split()
170 while args[0] in self.aliases:
171 line = self.aliases[args[0]]
172 ii = 1
173 for tmpArg in args[1:]:
174 line = line.replace("%" + str(ii),
175 tmpArg)
176 ii = ii + 1
177 line = line.replace("%*", ' '.join(args[1:]))
178 args = line.split()
179 # split into ';;' separated commands
180 # unless it's an alias command
181 if args[0] != 'alias':
182 marker = line.find(';;')
183 if marker >= 0:
184 # queue up everything after marker
185 next = line[marker+2:].lstrip()
186 self.cmdqueue.append(next)
187 line = line[:marker].rstrip()
188 return line
190 # Command definitions, called by cmdloop()
191 # The argument is the remaining string on the command line
192 # Return true to exit from the command loop
194 do_h = cmd.Cmd.do_help
196 def do_EOF(self, arg):
197 return 0 # Don't die on EOF
199 def do_break(self, arg, temporary = 0):
200 # break [ ([filename:]lineno | function) [, "condition"] ]
201 if not arg:
202 if self.breaks: # There's at least one
203 print "Num Type Disp Enb Where"
204 for bp in bdb.Breakpoint.bpbynumber:
205 if bp:
206 bp.bpprint()
207 return
208 # parse arguments; comma has lowest precedence
209 # and cannot occur in filename
210 filename = None
211 lineno = None
212 cond = None
213 comma = arg.find(',')
214 if comma > 0:
215 # parse stuff after comma: "condition"
216 cond = arg[comma+1:].lstrip()
217 arg = arg[:comma].rstrip()
218 # parse stuff before comma: [filename:]lineno | function
219 colon = arg.rfind(':')
220 if colon >= 0:
221 filename = arg[:colon].rstrip()
222 f = self.lookupmodule(filename)
223 if not f:
224 print '*** ', `filename`,
225 print 'not found from sys.path'
226 return
227 else:
228 filename = f
229 arg = arg[colon+1:].lstrip()
230 try:
231 lineno = int(arg)
232 except ValueError, msg:
233 print '*** Bad lineno:', arg
234 return
235 else:
236 # no colon; can be lineno or function
237 try:
238 lineno = int(arg)
239 except ValueError:
240 try:
241 func = eval(arg,
242 self.curframe.f_globals,
243 self.curframe.f_locals)
244 except:
245 func = arg
246 try:
247 if hasattr(func, 'im_func'):
248 func = func.im_func
249 code = func.func_code
250 lineno = code.co_firstlineno
251 filename = code.co_filename
252 except:
253 # last thing to try
254 (ok, filename, ln) = self.lineinfo(arg)
255 if not ok:
256 print '*** The specified object',
257 print `arg`,
258 print 'is not a function'
259 print ('or was not found '
260 'along sys.path.')
261 return
262 lineno = int(ln)
263 if not filename:
264 filename = self.defaultFile()
265 # Check for reasonable breakpoint
266 line = self.checkline(filename, lineno)
267 if line:
268 # now set the break point
269 err = self.set_break(filename, line, temporary, cond)
270 if err: print '***', err
271 else:
272 bp = self.get_breaks(filename, line)[-1]
273 print "Breakpoint %d at %s:%d" % (bp.number,
274 bp.file,
275 bp.line)
277 # To be overridden in derived debuggers
278 def defaultFile(self):
279 """Produce a reasonable default."""
280 filename = self.curframe.f_code.co_filename
281 if filename == '<string>' and mainpyfile:
282 filename = mainpyfile
283 return filename
285 do_b = do_break
287 def do_tbreak(self, arg):
288 self.do_break(arg, 1)
290 def lineinfo(self, identifier):
291 failed = (None, None, None)
292 # Input is identifier, may be in single quotes
293 idstring = identifier.split("'")
294 if len(idstring) == 1:
295 # not in single quotes
296 id = idstring[0].strip()
297 elif len(idstring) == 3:
298 # quoted
299 id = idstring[1].strip()
300 else:
301 return failed
302 if id == '': return failed
303 parts = id.split('.')
304 # Protection for derived debuggers
305 if parts[0] == 'self':
306 del parts[0]
307 if len(parts) == 0:
308 return failed
309 # Best first guess at file to look at
310 fname = self.defaultFile()
311 if len(parts) == 1:
312 item = parts[0]
313 else:
314 # More than one part.
315 # First is module, second is method/class
316 f = self.lookupmodule(parts[0])
317 if f:
318 fname = f
319 item = parts[1]
320 answer = find_function(item, fname)
321 return answer or failed
323 def checkline(self, filename, lineno):
324 """Return line number of first line at or after input
325 argument such that if the input points to a 'def', the
326 returned line number is the first
327 non-blank/non-comment line to follow. If the input
328 points to a blank or comment line, return 0. At end
329 of file, also return 0."""
331 line = linecache.getline(filename, lineno)
332 if not line:
333 print 'End of file'
334 return 0
335 line = line.strip()
336 # Don't allow setting breakpoint at a blank line
337 if (not line or (line[0] == '#') or
338 (line[:3] == '"""') or line[:3] == "'''"):
339 print '*** Blank or comment'
340 return 0
341 # When a file is read in and a breakpoint is at
342 # the 'def' statement, the system stops there at
343 # code parse time. We don't want that, so all breakpoints
344 # set at 'def' statements are moved one line onward
345 if line[:3] == 'def':
346 instr = ''
347 brackets = 0
348 while 1:
349 skipone = 0
350 for c in line:
351 if instr:
352 if skipone:
353 skipone = 0
354 elif c == '\\':
355 skipone = 1
356 elif c == instr:
357 instr = ''
358 elif c == '#':
359 break
360 elif c in ('"',"'"):
361 instr = c
362 elif c in ('(','{','['):
363 brackets = brackets + 1
364 elif c in (')','}',']'):
365 brackets = brackets - 1
366 lineno = lineno+1
367 line = linecache.getline(filename, lineno)
368 if not line:
369 print 'end of file'
370 return 0
371 line = line.strip()
372 if not line: continue # Blank line
373 if brackets <= 0 and line[0] not in ('#','"',"'"):
374 break
375 return lineno
377 def do_enable(self, arg):
378 args = arg.split()
379 for i in args:
380 bp = bdb.Breakpoint.bpbynumber[int(i)]
381 if bp:
382 bp.enable()
384 def do_disable(self, arg):
385 args = arg.split()
386 for i in args:
387 bp = bdb.Breakpoint.bpbynumber[int(i)]
388 if bp:
389 bp.disable()
391 def do_condition(self, arg):
392 # arg is breakpoint number and condition
393 args = arg.split(' ', 1)
394 bpnum = int(args[0].strip())
395 try:
396 cond = args[1]
397 except:
398 cond = None
399 bp = bdb.Breakpoint.bpbynumber[bpnum]
400 if bp:
401 bp.cond = cond
402 if not cond:
403 print 'Breakpoint', bpnum,
404 print 'is now unconditional.'
406 def do_ignore(self,arg):
407 """arg is bp number followed by ignore count."""
408 args = arg.split()
409 bpnum = int(args[0].strip())
410 try:
411 count = int(args[1].strip())
412 except:
413 count = 0
414 bp = bdb.Breakpoint.bpbynumber[bpnum]
415 if bp:
416 bp.ignore = count
417 if count > 0:
418 reply = 'Will ignore next '
419 if count > 1:
420 reply = reply + '%d crossings' % count
421 else:
422 reply = reply + '1 crossing'
423 print reply + ' of breakpoint %d.' % bpnum
424 else:
425 print 'Will stop next time breakpoint',
426 print bpnum, 'is reached.'
428 def do_clear(self, arg):
429 """Three possibilities, tried in this order:
430 clear -> clear all breaks, ask for confirmation
431 clear file:lineno -> clear all breaks at file:lineno
432 clear bpno bpno ... -> clear breakpoints by number"""
433 if not arg:
434 try:
435 reply = raw_input('Clear all breaks? ')
436 except EOFError:
437 reply = 'no'
438 reply = reply.strip().lower()
439 if reply in ('y', 'yes'):
440 self.clear_all_breaks()
441 return
442 if ':' in arg:
443 # Make sure it works for "clear C:\foo\bar.py:12"
444 i = arg.rfind(':')
445 filename = arg[:i]
446 arg = arg[i+1:]
447 try:
448 lineno = int(arg)
449 except:
450 err = "Invalid line number (%s)" % arg
451 else:
452 err = self.clear_break(filename, lineno)
453 if err: print '***', err
454 return
455 numberlist = arg.split()
456 for i in numberlist:
457 err = self.clear_bpbynumber(i)
458 if err:
459 print '***', err
460 else:
461 print 'Deleted breakpoint %s ' % (i,)
462 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
464 def do_where(self, arg):
465 self.print_stack_trace()
466 do_w = do_where
467 do_bt = do_where
469 def do_up(self, arg):
470 if self.curindex == 0:
471 print '*** Oldest frame'
472 else:
473 self.curindex = self.curindex - 1
474 self.curframe = self.stack[self.curindex][0]
475 self.print_stack_entry(self.stack[self.curindex])
476 self.lineno = None
477 do_u = do_up
479 def do_down(self, arg):
480 if self.curindex + 1 == len(self.stack):
481 print '*** Newest frame'
482 else:
483 self.curindex = self.curindex + 1
484 self.curframe = self.stack[self.curindex][0]
485 self.print_stack_entry(self.stack[self.curindex])
486 self.lineno = None
487 do_d = do_down
489 def do_step(self, arg):
490 self.set_step()
491 return 1
492 do_s = do_step
494 def do_next(self, arg):
495 self.set_next(self.curframe)
496 return 1
497 do_n = do_next
499 def do_return(self, arg):
500 self.set_return(self.curframe)
501 return 1
502 do_r = do_return
504 def do_continue(self, arg):
505 self.set_continue()
506 return 1
507 do_c = do_cont = do_continue
509 def do_jump(self, arg):
510 if self.curindex + 1 != len(self.stack):
511 print "*** You can only jump within the bottom frame"
512 return
513 try:
514 arg = int(arg)
515 except ValueError:
516 print "*** The 'jump' command requires a line number."
517 else:
518 try:
519 # Do the jump, fix up our copy of the stack, and display the
520 # new position
521 self.curframe.f_lineno = arg
522 self.stack[self.curindex] = self.stack[self.curindex][0], arg
523 self.print_stack_entry(self.stack[self.curindex])
524 except ValueError, e:
525 print '*** Jump failed:', e
526 do_j = do_jump
528 def do_quit(self, arg):
529 self.set_quit()
530 return 1
531 do_q = do_quit
532 do_exit = do_quit
534 def do_args(self, arg):
535 f = self.curframe
536 co = f.f_code
537 dict = f.f_locals
538 n = co.co_argcount
539 if co.co_flags & 4: n = n+1
540 if co.co_flags & 8: n = n+1
541 for i in range(n):
542 name = co.co_varnames[i]
543 print name, '=',
544 if name in dict: print dict[name]
545 else: print "*** undefined ***"
546 do_a = do_args
548 def do_retval(self, arg):
549 if '__return__' in self.curframe.f_locals:
550 print self.curframe.f_locals['__return__']
551 else:
552 print '*** Not yet returned!'
553 do_rv = do_retval
555 def _getval(self, arg):
556 try:
557 return eval(arg, self.curframe.f_globals,
558 self.curframe.f_locals)
559 except:
560 t, v = sys.exc_info()[:2]
561 if isinstance(t, str):
562 exc_type_name = t
563 else: exc_type_name = t.__name__
564 print '***', exc_type_name + ':', `v`
565 raise
567 def do_p(self, arg):
568 try:
569 print repr(self._getval(arg))
570 except:
571 pass
573 def do_pp(self, arg):
574 try:
575 pprint.pprint(self._getval(arg))
576 except:
577 pass
579 def do_list(self, arg):
580 self.lastcmd = 'list'
581 last = None
582 if arg:
583 try:
584 x = eval(arg, {}, {})
585 if type(x) == type(()):
586 first, last = x
587 first = int(first)
588 last = int(last)
589 if last < first:
590 # Assume it's a count
591 last = first + last
592 else:
593 first = max(1, int(x) - 5)
594 except:
595 print '*** Error in argument:', `arg`
596 return
597 elif self.lineno is None:
598 first = max(1, self.curframe.f_lineno - 5)
599 else:
600 first = self.lineno + 1
601 if last is None:
602 last = first + 10
603 filename = self.curframe.f_code.co_filename
604 breaklist = self.get_file_breaks(filename)
605 try:
606 for lineno in range(first, last+1):
607 line = linecache.getline(filename, lineno)
608 if not line:
609 print '[EOF]'
610 break
611 else:
612 s = `lineno`.rjust(3)
613 if len(s) < 4: s = s + ' '
614 if lineno in breaklist: s = s + 'B'
615 else: s = s + ' '
616 if lineno == self.curframe.f_lineno:
617 s = s + '->'
618 print s + '\t' + line,
619 self.lineno = lineno
620 except KeyboardInterrupt:
621 pass
622 do_l = do_list
624 def do_whatis(self, arg):
625 try:
626 value = eval(arg, self.curframe.f_globals,
627 self.curframe.f_locals)
628 except:
629 t, v = sys.exc_info()[:2]
630 if type(t) == type(''):
631 exc_type_name = t
632 else: exc_type_name = t.__name__
633 print '***', exc_type_name + ':', `v`
634 return
635 code = None
636 # Is it a function?
637 try: code = value.func_code
638 except: pass
639 if code:
640 print 'Function', code.co_name
641 return
642 # Is it an instance method?
643 try: code = value.im_func.func_code
644 except: pass
645 if code:
646 print 'Method', code.co_name
647 return
648 # None of the above...
649 print type(value)
651 def do_alias(self, arg):
652 args = arg.split()
653 if len(args) == 0:
654 keys = self.aliases.keys()
655 keys.sort()
656 for alias in keys:
657 print "%s = %s" % (alias, self.aliases[alias])
658 return
659 if args[0] in self.aliases and len(args) == 1:
660 print "%s = %s" % (args[0], self.aliases[args[0]])
661 else:
662 self.aliases[args[0]] = ' '.join(args[1:])
664 def do_unalias(self, arg):
665 args = arg.split()
666 if len(args) == 0: return
667 if args[0] in self.aliases:
668 del self.aliases[args[0]]
670 # Print a traceback starting at the top stack frame.
671 # The most recently entered frame is printed last;
672 # this is different from dbx and gdb, but consistent with
673 # the Python interpreter's stack trace.
674 # It is also consistent with the up/down commands (which are
675 # compatible with dbx and gdb: up moves towards 'main()'
676 # and down moves towards the most recent stack frame).
678 def print_stack_trace(self):
679 try:
680 for frame_lineno in self.stack:
681 self.print_stack_entry(frame_lineno)
682 except KeyboardInterrupt:
683 pass
685 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
686 frame, lineno = frame_lineno
687 if frame is self.curframe:
688 print '>',
689 else:
690 print ' ',
691 print self.format_stack_entry(frame_lineno, prompt_prefix)
694 # Help methods (derived from pdb.doc)
696 def help_help(self):
697 self.help_h()
699 def help_h(self):
700 print """h(elp)
701 Without argument, print the list of available commands.
702 With a command name as argument, print help about that command
703 "help pdb" pipes the full documentation file to the $PAGER
704 "help exec" gives help on the ! command"""
706 def help_where(self):
707 self.help_w()
709 def help_w(self):
710 print """w(here)
711 Print a stack trace, with the most recent frame at the bottom.
712 An arrow indicates the "current frame", which determines the
713 context of most commands. 'bt' is an alias for this command."""
715 help_bt = help_w
717 def help_down(self):
718 self.help_d()
720 def help_d(self):
721 print """d(own)
722 Move the current frame one level down in the stack trace
723 (to an older frame)."""
725 def help_up(self):
726 self.help_u()
728 def help_u(self):
729 print """u(p)
730 Move the current frame one level up in the stack trace
731 (to a newer frame)."""
733 def help_break(self):
734 self.help_b()
736 def help_b(self):
737 print """b(reak) ([file:]lineno | function) [, condition]
738 With a line number argument, set a break there in the current
739 file. With a function name, set a break at first executable line
740 of that function. Without argument, list all breaks. If a second
741 argument is present, it is a string specifying an expression
742 which must evaluate to true before the breakpoint is honored.
744 The line number may be prefixed with a filename and a colon,
745 to specify a breakpoint in another file (probably one that
746 hasn't been loaded yet). The file is searched for on sys.path;
747 the .py suffix may be omitted."""
749 def help_clear(self):
750 self.help_cl()
752 def help_cl(self):
753 print "cl(ear) filename:lineno"
754 print """cl(ear) [bpnumber [bpnumber...]]
755 With a space separated list of breakpoint numbers, clear
756 those breakpoints. Without argument, clear all breaks (but
757 first ask confirmation). With a filename:lineno argument,
758 clear all breaks at that line in that file.
760 Note that the argument is different from previous versions of
761 the debugger (in python distributions 1.5.1 and before) where
762 a linenumber was used instead of either filename:lineno or
763 breakpoint numbers."""
765 def help_tbreak(self):
766 print """tbreak same arguments as break, but breakpoint is
767 removed when first hit."""
769 def help_enable(self):
770 print """enable bpnumber [bpnumber ...]
771 Enables the breakpoints given as a space separated list of
772 bp numbers."""
774 def help_disable(self):
775 print """disable bpnumber [bpnumber ...]
776 Disables the breakpoints given as a space separated list of
777 bp numbers."""
779 def help_ignore(self):
780 print """ignore bpnumber count
781 Sets the ignore count for the given breakpoint number. A breakpoint
782 becomes active when the ignore count is zero. When non-zero, the
783 count is decremented each time the breakpoint is reached and the
784 breakpoint is not disabled and any associated condition evaluates
785 to true."""
787 def help_condition(self):
788 print """condition bpnumber str_condition
789 str_condition is a string specifying an expression which
790 must evaluate to true before the breakpoint is honored.
791 If str_condition is absent, any existing condition is removed;
792 i.e., the breakpoint is made unconditional."""
794 def help_step(self):
795 self.help_s()
797 def help_s(self):
798 print """s(tep)
799 Execute the current line, stop at the first possible occasion
800 (either in a function that is called or in the current function)."""
802 def help_next(self):
803 self.help_n()
805 def help_n(self):
806 print """n(ext)
807 Continue execution until the next line in the current function
808 is reached or it returns."""
810 def help_return(self):
811 self.help_r()
813 def help_r(self):
814 print """r(eturn)
815 Continue execution until the current function returns."""
817 def help_continue(self):
818 self.help_c()
820 def help_cont(self):
821 self.help_c()
823 def help_c(self):
824 print """c(ont(inue))
825 Continue execution, only stop when a breakpoint is encountered."""
827 def help_jump(self):
828 self.help_j()
830 def help_j(self):
831 print """j(ump) lineno
832 Set the next line that will be executed."""
834 def help_list(self):
835 self.help_l()
837 def help_l(self):
838 print """l(ist) [first [,last]]
839 List source code for the current file.
840 Without arguments, list 11 lines around the current line
841 or continue the previous listing.
842 With one argument, list 11 lines starting at that line.
843 With two arguments, list the given range;
844 if the second argument is less than the first, it is a count."""
846 def help_args(self):
847 self.help_a()
849 def help_a(self):
850 print """a(rgs)
851 Print the arguments of the current function."""
853 def help_p(self):
854 print """p expression
855 Print the value of the expression."""
857 def help_pp(self):
858 print """pp expression
859 Pretty-print the value of the expression."""
861 def help_exec(self):
862 print """(!) statement
863 Execute the (one-line) statement in the context of
864 the current stack frame.
865 The exclamation point can be omitted unless the first word
866 of the statement resembles a debugger command.
867 To assign to a global variable you must always prefix the
868 command with a 'global' command, e.g.:
869 (Pdb) global list_options; list_options = ['-l']
870 (Pdb)"""
872 def help_quit(self):
873 self.help_q()
875 def help_q(self):
876 print """q(uit) or exit - Quit from the debugger.
877 The program being executed is aborted."""
879 help_exit = help_q
881 def help_whatis(self):
882 print """whatis arg
883 Prints the type of the argument."""
885 def help_EOF(self):
886 print """EOF
887 Handles the receipt of EOF as a command."""
889 def help_alias(self):
890 print """alias [name [command [parameter parameter ...] ]]
891 Creates an alias called 'name' the executes 'command'. The command
892 must *not* be enclosed in quotes. Replaceable parameters are
893 indicated by %1, %2, and so on, while %* is replaced by all the
894 parameters. If no command is given, the current alias for name
895 is shown. If no name is given, all aliases are listed.
897 Aliases may be nested and can contain anything that can be
898 legally typed at the pdb prompt. Note! You *can* override
899 internal pdb commands with aliases! Those internal commands
900 are then hidden until the alias is removed. Aliasing is recursively
901 applied to the first word of the command line; all other words
902 in the line are left alone.
904 Some useful aliases (especially when placed in the .pdbrc file) are:
906 #Print instance variables (usage "pi classInst")
907 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
909 #Print instance variables in self
910 alias ps pi self
913 def help_unalias(self):
914 print """unalias name
915 Deletes the specified alias."""
917 def help_pdb(self):
918 help()
920 def lookupmodule(self, filename):
921 """Helper function for break/clear parsing -- may be overridden."""
922 root, ext = os.path.splitext(filename)
923 if ext == '':
924 filename = filename + '.py'
925 if os.path.isabs(filename):
926 return filename
927 for dirname in sys.path:
928 while os.path.islink(dirname):
929 dirname = os.readlink(dirname)
930 fullname = os.path.join(dirname, filename)
931 if os.path.exists(fullname):
932 return fullname
933 return None
935 # Simplified interface
937 def run(statement, globals=None, locals=None):
938 Pdb().run(statement, globals, locals)
940 def runeval(expression, globals=None, locals=None):
941 return Pdb().runeval(expression, globals, locals)
943 def runctx(statement, globals, locals):
944 # B/W compatibility
945 run(statement, globals, locals)
947 def runcall(*args):
948 return apply(Pdb().runcall, args)
950 def set_trace():
951 Pdb().set_trace()
953 # Post-Mortem interface
955 def post_mortem(t):
956 p = Pdb()
957 p.reset()
958 while t.tb_next is not None:
959 t = t.tb_next
960 p.interaction(t.tb_frame, t)
962 def pm():
963 post_mortem(sys.last_traceback)
966 # Main program for testing
968 TESTCMD = 'import x; x.main()'
970 def test():
971 run(TESTCMD)
973 # print help
974 def help():
975 for dirname in sys.path:
976 fullname = os.path.join(dirname, 'pdb.doc')
977 if os.path.exists(fullname):
978 sts = os.system('${PAGER-more} '+fullname)
979 if sts: print '*** Pager exit status:', sts
980 break
981 else:
982 print 'Sorry, can\'t find the help file "pdb.doc"',
983 print 'along the Python search path'
985 mainmodule = ''
986 mainpyfile = ''
988 # When invoked as main program, invoke the debugger on a script
989 if __name__=='__main__':
990 if not sys.argv[1:]:
991 print "usage: pdb.py scriptfile [arg] ..."
992 sys.exit(2)
994 mainpyfile = filename = sys.argv[1] # Get script filename
995 if not os.path.exists(filename):
996 print 'Error:', `filename`, 'does not exist'
997 sys.exit(1)
998 mainmodule = os.path.basename(filename)
999 del sys.argv[0] # Hide "pdb.py" from argument list
1001 # Insert script directory in front of module search path
1002 sys.path.insert(0, os.path.dirname(filename))
1004 run('execfile(' + `filename` + ')')