Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v8plus / lib / python2.4 / pdb.py
CommitLineData
920dae64
AT
1#! /usr/bin/env python
2
3"""A Python debugger."""
4
5# (See pdb.doc for documentation.)
6
7import sys
8import linecache
9import cmd
10import bdb
11from repr import Repr
12import os
13import re
14import pprint
15import traceback
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
21
22__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
23 "post_mortem", "help"]
24
25def 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
44
45
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
51line_prefix = '\n-> ' # Probably a better default
52
53class Pdb(bdb.Bdb, cmd.Cmd):
54
55 def __init__(self):
56 bdb.Bdb.__init__(self)
57 cmd.Cmd.__init__(self)
58 self.prompt = '(Pdb) '
59 self.aliases = {}
60 self.mainpyfile = ''
61 self._wait_for_mainpyfile = 0
62 # Try to load readline if it exists
63 try:
64 import readline
65 except ImportError:
66 pass
67
68 # Read $HOME/.pdbrc and ./.pdbrc
69 self.rcLines = []
70 if 'HOME' in os.environ:
71 envHome = os.environ['HOME']
72 try:
73 rcFile = open(os.path.join(envHome, ".pdbrc"))
74 except IOError:
75 pass
76 else:
77 for line in rcFile.readlines():
78 self.rcLines.append(line)
79 rcFile.close()
80 try:
81 rcFile = open(".pdbrc")
82 except IOError:
83 pass
84 else:
85 for line in rcFile.readlines():
86 self.rcLines.append(line)
87 rcFile.close()
88
89 def reset(self):
90 bdb.Bdb.reset(self)
91 self.forget()
92
93 def forget(self):
94 self.lineno = None
95 self.stack = []
96 self.curindex = 0
97 self.curframe = None
98
99 def setup(self, f, t):
100 self.forget()
101 self.stack, self.curindex = self.get_stack(f, t)
102 self.curframe = self.stack[self.curindex][0]
103 self.execRcLines()
104
105 # Can be executed earlier than 'setup' if desired
106 def execRcLines(self):
107 if self.rcLines:
108 # Make local copy because of recursion
109 rcLines = self.rcLines
110 # executed only once
111 self.rcLines = []
112 for line in rcLines:
113 line = line[:-1]
114 if len(line) > 0 and line[0] != '#':
115 self.onecmd(line)
116
117 # Override Bdb methods
118
119 def user_call(self, frame, argument_list):
120 """This method is called when there is the remote possibility
121 that we ever need to stop in this function."""
122 if self._wait_for_mainpyfile:
123 return
124 if self.stop_here(frame):
125 print '--Call--'
126 self.interaction(frame, None)
127
128 def user_line(self, frame):
129 """This function is called when we stop or break at this line."""
130 if self._wait_for_mainpyfile:
131 if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
132 or frame.f_lineno<= 0):
133 return
134 self._wait_for_mainpyfile = 0
135 self.interaction(frame, None)
136
137 def user_return(self, frame, return_value):
138 """This function is called when a return trap is set here."""
139 frame.f_locals['__return__'] = return_value
140 print '--Return--'
141 self.interaction(frame, None)
142
143 def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
144 """This function is called if an exception occurs,
145 but only if we are to stop at or just below this level."""
146 frame.f_locals['__exception__'] = exc_type, exc_value
147 if type(exc_type) == type(''):
148 exc_type_name = exc_type
149 else: exc_type_name = exc_type.__name__
150 print exc_type_name + ':', _saferepr(exc_value)
151 self.interaction(frame, exc_traceback)
152
153 # General interaction function
154
155 def interaction(self, frame, traceback):
156 self.setup(frame, traceback)
157 self.print_stack_entry(self.stack[self.curindex])
158 self.cmdloop()
159 self.forget()
160
161 def default(self, line):
162 if line[:1] == '!': line = line[1:]
163 locals = self.curframe.f_locals
164 globals = self.curframe.f_globals
165 try:
166 code = compile(line + '\n', '<stdin>', 'single')
167 exec code in globals, locals
168 except:
169 t, v = sys.exc_info()[:2]
170 if type(t) == type(''):
171 exc_type_name = t
172 else: exc_type_name = t.__name__
173 print '***', exc_type_name + ':', v
174
175 def precmd(self, line):
176 """Handle alias expansion and ';;' separator."""
177 if not line.strip():
178 return line
179 args = line.split()
180 while args[0] in self.aliases:
181 line = self.aliases[args[0]]
182 ii = 1
183 for tmpArg in args[1:]:
184 line = line.replace("%" + str(ii),
185 tmpArg)
186 ii = ii + 1
187 line = line.replace("%*", ' '.join(args[1:]))
188 args = line.split()
189 # split into ';;' separated commands
190 # unless it's an alias command
191 if args[0] != 'alias':
192 marker = line.find(';;')
193 if marker >= 0:
194 # queue up everything after marker
195 next = line[marker+2:].lstrip()
196 self.cmdqueue.append(next)
197 line = line[:marker].rstrip()
198 return line
199
200 # Command definitions, called by cmdloop()
201 # The argument is the remaining string on the command line
202 # Return true to exit from the command loop
203
204 do_h = cmd.Cmd.do_help
205
206 def do_break(self, arg, temporary = 0):
207 # break [ ([filename:]lineno | function) [, "condition"] ]
208 if not arg:
209 if self.breaks: # There's at least one
210 print "Num Type Disp Enb Where"
211 for bp in bdb.Breakpoint.bpbynumber:
212 if bp:
213 bp.bpprint()
214 return
215 # parse arguments; comma has lowest precedence
216 # and cannot occur in filename
217 filename = None
218 lineno = None
219 cond = None
220 comma = arg.find(',')
221 if comma > 0:
222 # parse stuff after comma: "condition"
223 cond = arg[comma+1:].lstrip()
224 arg = arg[:comma].rstrip()
225 # parse stuff before comma: [filename:]lineno | function
226 colon = arg.rfind(':')
227 funcname = None
228 if colon >= 0:
229 filename = arg[:colon].rstrip()
230 f = self.lookupmodule(filename)
231 if not f:
232 print '*** ', repr(filename),
233 print 'not found from sys.path'
234 return
235 else:
236 filename = f
237 arg = arg[colon+1:].lstrip()
238 try:
239 lineno = int(arg)
240 except ValueError, msg:
241 print '*** Bad lineno:', arg
242 return
243 else:
244 # no colon; can be lineno or function
245 try:
246 lineno = int(arg)
247 except ValueError:
248 try:
249 func = eval(arg,
250 self.curframe.f_globals,
251 self.curframe.f_locals)
252 except:
253 func = arg
254 try:
255 if hasattr(func, 'im_func'):
256 func = func.im_func
257 code = func.func_code
258 #use co_name to identify the bkpt (function names
259 #could be aliased, but co_name is invariant)
260 funcname = code.co_name
261 lineno = code.co_firstlineno
262 filename = code.co_filename
263 except:
264 # last thing to try
265 (ok, filename, ln) = self.lineinfo(arg)
266 if not ok:
267 print '*** The specified object',
268 print repr(arg),
269 print 'is not a function'
270 print ('or was not found '
271 'along sys.path.')
272 return
273 funcname = ok # ok contains a function name
274 lineno = int(ln)
275 if not filename:
276 filename = self.defaultFile()
277 # Check for reasonable breakpoint
278 line = self.checkline(filename, lineno)
279 if line:
280 # now set the break point
281 err = self.set_break(filename, line, temporary, cond, funcname)
282 if err: print '***', err
283 else:
284 bp = self.get_breaks(filename, line)[-1]
285 print "Breakpoint %d at %s:%d" % (bp.number,
286 bp.file,
287 bp.line)
288
289 # To be overridden in derived debuggers
290 def defaultFile(self):
291 """Produce a reasonable default."""
292 filename = self.curframe.f_code.co_filename
293 if filename == '<string>' and self.mainpyfile:
294 filename = self.mainpyfile
295 return filename
296
297 do_b = do_break
298
299 def do_tbreak(self, arg):
300 self.do_break(arg, 1)
301
302 def lineinfo(self, identifier):
303 failed = (None, None, None)
304 # Input is identifier, may be in single quotes
305 idstring = identifier.split("'")
306 if len(idstring) == 1:
307 # not in single quotes
308 id = idstring[0].strip()
309 elif len(idstring) == 3:
310 # quoted
311 id = idstring[1].strip()
312 else:
313 return failed
314 if id == '': return failed
315 parts = id.split('.')
316 # Protection for derived debuggers
317 if parts[0] == 'self':
318 del parts[0]
319 if len(parts) == 0:
320 return failed
321 # Best first guess at file to look at
322 fname = self.defaultFile()
323 if len(parts) == 1:
324 item = parts[0]
325 else:
326 # More than one part.
327 # First is module, second is method/class
328 f = self.lookupmodule(parts[0])
329 if f:
330 fname = f
331 item = parts[1]
332 answer = find_function(item, fname)
333 return answer or failed
334
335 def checkline(self, filename, lineno):
336 """Check whether specified line seems to be executable.
337
338 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
339 line or EOF). Warning: testing is not comprehensive.
340 """
341 line = linecache.getline(filename, lineno)
342 if not line:
343 print 'End of file'
344 return 0
345 line = line.strip()
346 # Don't allow setting breakpoint at a blank line
347 if (not line or (line[0] == '#') or
348 (line[:3] == '"""') or line[:3] == "'''"):
349 print '*** Blank or comment'
350 return 0
351 return lineno
352
353 def do_enable(self, arg):
354 args = arg.split()
355 for i in args:
356 try:
357 i = int(i)
358 except ValueError:
359 print 'Breakpoint index %r is not a number' % i
360 continue
361
362 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
363 print 'No breakpoint numbered', i
364 continue
365
366 bp = bdb.Breakpoint.bpbynumber[i]
367 if bp:
368 bp.enable()
369
370 def do_disable(self, arg):
371 args = arg.split()
372 for i in args:
373 try:
374 i = int(i)
375 except ValueError:
376 print 'Breakpoint index %r is not a number' % i
377 continue
378
379 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
380 print 'No breakpoint numbered', i
381 continue
382
383 bp = bdb.Breakpoint.bpbynumber[i]
384 if bp:
385 bp.disable()
386
387 def do_condition(self, arg):
388 # arg is breakpoint number and condition
389 args = arg.split(' ', 1)
390 bpnum = int(args[0].strip())
391 try:
392 cond = args[1]
393 except:
394 cond = None
395 bp = bdb.Breakpoint.bpbynumber[bpnum]
396 if bp:
397 bp.cond = cond
398 if not cond:
399 print 'Breakpoint', bpnum,
400 print 'is now unconditional.'
401
402 def do_ignore(self,arg):
403 """arg is bp number followed by ignore count."""
404 args = arg.split()
405 bpnum = int(args[0].strip())
406 try:
407 count = int(args[1].strip())
408 except:
409 count = 0
410 bp = bdb.Breakpoint.bpbynumber[bpnum]
411 if bp:
412 bp.ignore = count
413 if count > 0:
414 reply = 'Will ignore next '
415 if count > 1:
416 reply = reply + '%d crossings' % count
417 else:
418 reply = reply + '1 crossing'
419 print reply + ' of breakpoint %d.' % bpnum
420 else:
421 print 'Will stop next time breakpoint',
422 print bpnum, 'is reached.'
423
424 def do_clear(self, arg):
425 """Three possibilities, tried in this order:
426 clear -> clear all breaks, ask for confirmation
427 clear file:lineno -> clear all breaks at file:lineno
428 clear bpno bpno ... -> clear breakpoints by number"""
429 if not arg:
430 try:
431 reply = raw_input('Clear all breaks? ')
432 except EOFError:
433 reply = 'no'
434 reply = reply.strip().lower()
435 if reply in ('y', 'yes'):
436 self.clear_all_breaks()
437 return
438 if ':' in arg:
439 # Make sure it works for "clear C:\foo\bar.py:12"
440 i = arg.rfind(':')
441 filename = arg[:i]
442 arg = arg[i+1:]
443 try:
444 lineno = int(arg)
445 except:
446 err = "Invalid line number (%s)" % arg
447 else:
448 err = self.clear_break(filename, lineno)
449 if err: print '***', err
450 return
451 numberlist = arg.split()
452 for i in numberlist:
453 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
454 print 'No breakpoint numbered', i
455 continue
456 err = self.clear_bpbynumber(i)
457 if err:
458 print '***', err
459 else:
460 print 'Deleted breakpoint', i
461 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
462
463 def do_where(self, arg):
464 self.print_stack_trace()
465 do_w = do_where
466 do_bt = do_where
467
468 def do_up(self, arg):
469 if self.curindex == 0:
470 print '*** Oldest frame'
471 else:
472 self.curindex = self.curindex - 1
473 self.curframe = self.stack[self.curindex][0]
474 self.print_stack_entry(self.stack[self.curindex])
475 self.lineno = None
476 do_u = do_up
477
478 def do_down(self, arg):
479 if self.curindex + 1 == len(self.stack):
480 print '*** Newest frame'
481 else:
482 self.curindex = self.curindex + 1
483 self.curframe = self.stack[self.curindex][0]
484 self.print_stack_entry(self.stack[self.curindex])
485 self.lineno = None
486 do_d = do_down
487
488 def do_step(self, arg):
489 self.set_step()
490 return 1
491 do_s = do_step
492
493 def do_next(self, arg):
494 self.set_next(self.curframe)
495 return 1
496 do_n = do_next
497
498 def do_return(self, arg):
499 self.set_return(self.curframe)
500 return 1
501 do_r = do_return
502
503 def do_continue(self, arg):
504 self.set_continue()
505 return 1
506 do_c = do_cont = do_continue
507
508 def do_jump(self, arg):
509 if self.curindex + 1 != len(self.stack):
510 print "*** You can only jump within the bottom frame"
511 return
512 try:
513 arg = int(arg)
514 except ValueError:
515 print "*** The 'jump' command requires a line number."
516 else:
517 try:
518 # Do the jump, fix up our copy of the stack, and display the
519 # new position
520 self.curframe.f_lineno = arg
521 self.stack[self.curindex] = self.stack[self.curindex][0], arg
522 self.print_stack_entry(self.stack[self.curindex])
523 except ValueError, e:
524 print '*** Jump failed:', e
525 do_j = do_jump
526
527 def do_debug(self, arg):
528 sys.settrace(None)
529 globals = self.curframe.f_globals
530 locals = self.curframe.f_locals
531 p = Pdb()
532 p.prompt = "(%s) " % self.prompt.strip()
533 print "ENTERING RECURSIVE DEBUGGER"
534 sys.call_tracing(p.run, (arg, globals, locals))
535 print "LEAVING RECURSIVE DEBUGGER"
536 sys.settrace(self.trace_dispatch)
537 self.lastcmd = p.lastcmd
538
539 def do_quit(self, arg):
540 self._user_requested_quit = 1
541 self.set_quit()
542 return 1
543
544 do_q = do_quit
545 do_exit = do_quit
546
547 def do_EOF(self, arg):
548 print
549 self._user_requested_quit = 1
550 self.set_quit()
551 return 1
552
553 def do_args(self, arg):
554 f = self.curframe
555 co = f.f_code
556 dict = f.f_locals
557 n = co.co_argcount
558 if co.co_flags & 4: n = n+1
559 if co.co_flags & 8: n = n+1
560 for i in range(n):
561 name = co.co_varnames[i]
562 print name, '=',
563 if name in dict: print dict[name]
564 else: print "*** undefined ***"
565 do_a = do_args
566
567 def do_retval(self, arg):
568 if '__return__' in self.curframe.f_locals:
569 print self.curframe.f_locals['__return__']
570 else:
571 print '*** Not yet returned!'
572 do_rv = do_retval
573
574 def _getval(self, arg):
575 try:
576 return eval(arg, self.curframe.f_globals,
577 self.curframe.f_locals)
578 except:
579 t, v = sys.exc_info()[:2]
580 if isinstance(t, str):
581 exc_type_name = t
582 else: exc_type_name = t.__name__
583 print '***', exc_type_name + ':', repr(v)
584 raise
585
586 def do_p(self, arg):
587 try:
588 print repr(self._getval(arg))
589 except:
590 pass
591
592 def do_pp(self, arg):
593 try:
594 pprint.pprint(self._getval(arg))
595 except:
596 pass
597
598 def do_list(self, arg):
599 self.lastcmd = 'list'
600 last = None
601 if arg:
602 try:
603 x = eval(arg, {}, {})
604 if type(x) == type(()):
605 first, last = x
606 first = int(first)
607 last = int(last)
608 if last < first:
609 # Assume it's a count
610 last = first + last
611 else:
612 first = max(1, int(x) - 5)
613 except:
614 print '*** Error in argument:', repr(arg)
615 return
616 elif self.lineno is None:
617 first = max(1, self.curframe.f_lineno - 5)
618 else:
619 first = self.lineno + 1
620 if last is None:
621 last = first + 10
622 filename = self.curframe.f_code.co_filename
623 breaklist = self.get_file_breaks(filename)
624 try:
625 for lineno in range(first, last+1):
626 line = linecache.getline(filename, lineno)
627 if not line:
628 print '[EOF]'
629 break
630 else:
631 s = repr(lineno).rjust(3)
632 if len(s) < 4: s = s + ' '
633 if lineno in breaklist: s = s + 'B'
634 else: s = s + ' '
635 if lineno == self.curframe.f_lineno:
636 s = s + '->'
637 print s + '\t' + line,
638 self.lineno = lineno
639 except KeyboardInterrupt:
640 pass
641 do_l = do_list
642
643 def do_whatis(self, arg):
644 try:
645 value = eval(arg, self.curframe.f_globals,
646 self.curframe.f_locals)
647 except:
648 t, v = sys.exc_info()[:2]
649 if type(t) == type(''):
650 exc_type_name = t
651 else: exc_type_name = t.__name__
652 print '***', exc_type_name + ':', repr(v)
653 return
654 code = None
655 # Is it a function?
656 try: code = value.func_code
657 except: pass
658 if code:
659 print 'Function', code.co_name
660 return
661 # Is it an instance method?
662 try: code = value.im_func.func_code
663 except: pass
664 if code:
665 print 'Method', code.co_name
666 return
667 # None of the above...
668 print type(value)
669
670 def do_alias(self, arg):
671 args = arg.split()
672 if len(args) == 0:
673 keys = self.aliases.keys()
674 keys.sort()
675 for alias in keys:
676 print "%s = %s" % (alias, self.aliases[alias])
677 return
678 if args[0] in self.aliases and len(args) == 1:
679 print "%s = %s" % (args[0], self.aliases[args[0]])
680 else:
681 self.aliases[args[0]] = ' '.join(args[1:])
682
683 def do_unalias(self, arg):
684 args = arg.split()
685 if len(args) == 0: return
686 if args[0] in self.aliases:
687 del self.aliases[args[0]]
688
689 # Print a traceback starting at the top stack frame.
690 # The most recently entered frame is printed last;
691 # this is different from dbx and gdb, but consistent with
692 # the Python interpreter's stack trace.
693 # It is also consistent with the up/down commands (which are
694 # compatible with dbx and gdb: up moves towards 'main()'
695 # and down moves towards the most recent stack frame).
696
697 def print_stack_trace(self):
698 try:
699 for frame_lineno in self.stack:
700 self.print_stack_entry(frame_lineno)
701 except KeyboardInterrupt:
702 pass
703
704 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
705 frame, lineno = frame_lineno
706 if frame is self.curframe:
707 print '>',
708 else:
709 print ' ',
710 print self.format_stack_entry(frame_lineno, prompt_prefix)
711
712
713 # Help methods (derived from pdb.doc)
714
715 def help_help(self):
716 self.help_h()
717
718 def help_h(self):
719 print """h(elp)
720Without argument, print the list of available commands.
721With a command name as argument, print help about that command
722"help pdb" pipes the full documentation file to the $PAGER
723"help exec" gives help on the ! command"""
724
725 def help_where(self):
726 self.help_w()
727
728 def help_w(self):
729 print """w(here)
730Print a stack trace, with the most recent frame at the bottom.
731An arrow indicates the "current frame", which determines the
732context of most commands. 'bt' is an alias for this command."""
733
734 help_bt = help_w
735
736 def help_down(self):
737 self.help_d()
738
739 def help_d(self):
740 print """d(own)
741Move the current frame one level down in the stack trace
742(to a newer frame)."""
743
744 def help_up(self):
745 self.help_u()
746
747 def help_u(self):
748 print """u(p)
749Move the current frame one level up in the stack trace
750(to an older frame)."""
751
752 def help_break(self):
753 self.help_b()
754
755 def help_b(self):
756 print """b(reak) ([file:]lineno | function) [, condition]
757With a line number argument, set a break there in the current
758file. With a function name, set a break at first executable line
759of that function. Without argument, list all breaks. If a second
760argument is present, it is a string specifying an expression
761which must evaluate to true before the breakpoint is honored.
762
763The line number may be prefixed with a filename and a colon,
764to specify a breakpoint in another file (probably one that
765hasn't been loaded yet). The file is searched for on sys.path;
766the .py suffix may be omitted."""
767
768 def help_clear(self):
769 self.help_cl()
770
771 def help_cl(self):
772 print "cl(ear) filename:lineno"
773 print """cl(ear) [bpnumber [bpnumber...]]
774With a space separated list of breakpoint numbers, clear
775those breakpoints. Without argument, clear all breaks (but
776first ask confirmation). With a filename:lineno argument,
777clear all breaks at that line in that file.
778
779Note that the argument is different from previous versions of
780the debugger (in python distributions 1.5.1 and before) where
781a linenumber was used instead of either filename:lineno or
782breakpoint numbers."""
783
784 def help_tbreak(self):
785 print """tbreak same arguments as break, but breakpoint is
786removed when first hit."""
787
788 def help_enable(self):
789 print """enable bpnumber [bpnumber ...]
790Enables the breakpoints given as a space separated list of
791bp numbers."""
792
793 def help_disable(self):
794 print """disable bpnumber [bpnumber ...]
795Disables the breakpoints given as a space separated list of
796bp numbers."""
797
798 def help_ignore(self):
799 print """ignore bpnumber count
800Sets the ignore count for the given breakpoint number. A breakpoint
801becomes active when the ignore count is zero. When non-zero, the
802count is decremented each time the breakpoint is reached and the
803breakpoint is not disabled and any associated condition evaluates
804to true."""
805
806 def help_condition(self):
807 print """condition bpnumber str_condition
808str_condition is a string specifying an expression which
809must evaluate to true before the breakpoint is honored.
810If str_condition is absent, any existing condition is removed;
811i.e., the breakpoint is made unconditional."""
812
813 def help_step(self):
814 self.help_s()
815
816 def help_s(self):
817 print """s(tep)
818Execute the current line, stop at the first possible occasion
819(either in a function that is called or in the current function)."""
820
821 def help_next(self):
822 self.help_n()
823
824 def help_n(self):
825 print """n(ext)
826Continue execution until the next line in the current function
827is reached or it returns."""
828
829 def help_return(self):
830 self.help_r()
831
832 def help_r(self):
833 print """r(eturn)
834Continue execution until the current function returns."""
835
836 def help_continue(self):
837 self.help_c()
838
839 def help_cont(self):
840 self.help_c()
841
842 def help_c(self):
843 print """c(ont(inue))
844Continue execution, only stop when a breakpoint is encountered."""
845
846 def help_jump(self):
847 self.help_j()
848
849 def help_j(self):
850 print """j(ump) lineno
851Set the next line that will be executed."""
852
853 def help_debug(self):
854 print """debug code
855Enter a recursive debugger that steps through the code argument
856(which is an arbitrary expression or statement to be executed
857in the current environment)."""
858
859 def help_list(self):
860 self.help_l()
861
862 def help_l(self):
863 print """l(ist) [first [,last]]
864List source code for the current file.
865Without arguments, list 11 lines around the current line
866or continue the previous listing.
867With one argument, list 11 lines starting at that line.
868With two arguments, list the given range;
869if the second argument is less than the first, it is a count."""
870
871 def help_args(self):
872 self.help_a()
873
874 def help_a(self):
875 print """a(rgs)
876Print the arguments of the current function."""
877
878 def help_p(self):
879 print """p expression
880Print the value of the expression."""
881
882 def help_pp(self):
883 print """pp expression
884Pretty-print the value of the expression."""
885
886 def help_exec(self):
887 print """(!) statement
888Execute the (one-line) statement in the context of
889the current stack frame.
890The exclamation point can be omitted unless the first word
891of the statement resembles a debugger command.
892To assign to a global variable you must always prefix the
893command with a 'global' command, e.g.:
894(Pdb) global list_options; list_options = ['-l']
895(Pdb)"""
896
897 def help_quit(self):
898 self.help_q()
899
900 def help_q(self):
901 print """q(uit) or exit - Quit from the debugger.
902The program being executed is aborted."""
903
904 help_exit = help_q
905
906 def help_whatis(self):
907 print """whatis arg
908Prints the type of the argument."""
909
910 def help_EOF(self):
911 print """EOF
912Handles the receipt of EOF as a command."""
913
914 def help_alias(self):
915 print """alias [name [command [parameter parameter ...] ]]
916Creates an alias called 'name' the executes 'command'. The command
917must *not* be enclosed in quotes. Replaceable parameters are
918indicated by %1, %2, and so on, while %* is replaced by all the
919parameters. If no command is given, the current alias for name
920is shown. If no name is given, all aliases are listed.
921
922Aliases may be nested and can contain anything that can be
923legally typed at the pdb prompt. Note! You *can* override
924internal pdb commands with aliases! Those internal commands
925are then hidden until the alias is removed. Aliasing is recursively
926applied to the first word of the command line; all other words
927in the line are left alone.
928
929Some useful aliases (especially when placed in the .pdbrc file) are:
930
931#Print instance variables (usage "pi classInst")
932alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
933
934#Print instance variables in self
935alias ps pi self
936"""
937
938 def help_unalias(self):
939 print """unalias name
940Deletes the specified alias."""
941
942 def help_pdb(self):
943 help()
944
945 def lookupmodule(self, filename):
946 """Helper function for break/clear parsing -- may be overridden.
947
948 lookupmodule() translates (possibly incomplete) file or module name
949 into an absolute file name.
950 """
951 if os.path.isabs(filename) and os.path.exists(filename):
952 return filename
953 f = os.path.join(sys.path[0], filename)
954 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
955 return f
956 root, ext = os.path.splitext(filename)
957 if ext == '':
958 filename = filename + '.py'
959 if os.path.isabs(filename):
960 return filename
961 for dirname in sys.path:
962 while os.path.islink(dirname):
963 dirname = os.readlink(dirname)
964 fullname = os.path.join(dirname, filename)
965 if os.path.exists(fullname):
966 return fullname
967 return None
968
969 def _runscript(self, filename):
970 # Start with fresh empty copy of globals and locals and tell the script
971 # that it's being run as __main__ to avoid scripts being able to access
972 # the pdb.py namespace.
973 globals_ = {"__name__" : "__main__"}
974 locals_ = globals_
975
976 # When bdb sets tracing, a number of call and line events happens
977 # BEFORE debugger even reaches user's code (and the exact sequence of
978 # events depends on python version). So we take special measures to
979 # avoid stopping before we reach the main script (see user_line and
980 # user_call for details).
981 self._wait_for_mainpyfile = 1
982 self.mainpyfile = self.canonic(filename)
983 self._user_requested_quit = 0
984 statement = 'execfile( "%s")' % filename
985 self.run(statement, globals=globals_, locals=locals_)
986
987# Simplified interface
988
989def run(statement, globals=None, locals=None):
990 Pdb().run(statement, globals, locals)
991
992def runeval(expression, globals=None, locals=None):
993 return Pdb().runeval(expression, globals, locals)
994
995def runctx(statement, globals, locals):
996 # B/W compatibility
997 run(statement, globals, locals)
998
999def runcall(*args, **kwds):
1000 return Pdb().runcall(*args, **kwds)
1001
1002def set_trace():
1003 Pdb().set_trace(sys._getframe().f_back)
1004
1005# Post-Mortem interface
1006
1007def post_mortem(t):
1008 p = Pdb()
1009 p.reset()
1010 while t.tb_next is not None:
1011 t = t.tb_next
1012 p.interaction(t.tb_frame, t)
1013
1014def pm():
1015 post_mortem(sys.last_traceback)
1016
1017
1018# Main program for testing
1019
1020TESTCMD = 'import x; x.main()'
1021
1022def test():
1023 run(TESTCMD)
1024
1025# print help
1026def help():
1027 for dirname in sys.path:
1028 fullname = os.path.join(dirname, 'pdb.doc')
1029 if os.path.exists(fullname):
1030 sts = os.system('${PAGER-more} '+fullname)
1031 if sts: print '*** Pager exit status:', sts
1032 break
1033 else:
1034 print 'Sorry, can\'t find the help file "pdb.doc"',
1035 print 'along the Python search path'
1036
1037def main():
1038 if not sys.argv[1:]:
1039 print "usage: pdb.py scriptfile [arg] ..."
1040 sys.exit(2)
1041
1042 mainpyfile = sys.argv[1] # Get script filename
1043 if not os.path.exists(mainpyfile):
1044 print 'Error:', mainpyfile, 'does not exist'
1045 sys.exit(1)
1046
1047 del sys.argv[0] # Hide "pdb.py" from argument list
1048
1049 # Replace pdb's dir with script's dir in front of module search path.
1050 sys.path[0] = os.path.dirname(mainpyfile)
1051
1052 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1053 # modified by the script being debugged. It's a bad idea when it was
1054 # changed by the user from the command line. The best approach would be to
1055 # have a "restart" command which would allow explicit specification of
1056 # command line arguments.
1057 pdb = Pdb()
1058 while 1:
1059 try:
1060 pdb._runscript(mainpyfile)
1061 if pdb._user_requested_quit:
1062 break
1063 print "The program finished and will be restarted"
1064 except SystemExit:
1065 # In most cases SystemExit does not warrant a post-mortem session.
1066 print "The program exited via sys.exit(). Exit status: ",
1067 print sys.exc_info()[1]
1068 except:
1069 traceback.print_exc()
1070 print "Uncaught exception. Entering post mortem debugging"
1071 print "Running 'cont' or 'step' will restart the program"
1072 t = sys.exc_info()[2]
1073 while t.tb_next is not None:
1074 t = t.tb_next
1075 pdb.interaction(t.tb_frame,t)
1076 print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
1077
1078
1079# When invoked as main program, invoke the debugger on a script
1080if __name__=='__main__':
1081 main()