PyXR

c:\python24\lib \ pdb.py



0001 #! /usr/bin/env python
0002 
0003 """A Python debugger."""
0004 
0005 # (See pdb.doc for documentation.)
0006 
0007 import sys
0008 import linecache
0009 import cmd
0010 import bdb
0011 from repr import Repr
0012 import os
0013 import re
0014 import pprint
0015 import traceback
0016 # Create a custom safe Repr instance and increase its maxstring.
0017 # The default of 30 truncates error messages too easily.
0018 _repr = Repr()
0019 _repr.maxstring = 200
0020 _saferepr = _repr.repr
0021 
0022 __all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
0023            "post_mortem", "help"]
0024 
0025 def find_function(funcname, filename):
0026     cre = re.compile(r'def\s+%s\s*[(]' % funcname)
0027     try:
0028         fp = open(filename)
0029     except IOError:
0030         return None
0031     # consumer of this info expects the first line to be 1
0032     lineno = 1
0033     answer = None
0034     while 1:
0035         line = fp.readline()
0036         if line == '':
0037             break
0038         if cre.match(line):
0039             answer = funcname, filename, lineno
0040             break
0041         lineno = lineno + 1
0042     fp.close()
0043     return answer
0044 
0045 
0046 # Interaction prompt line will separate file and call info from code
0047 # text using value of line_prefix string.  A newline and arrow may
0048 # be to your liking.  You can set it once pdb is imported using the
0049 # command "pdb.line_prefix = '\n% '".
0050 # line_prefix = ': '    # Use this to get the old situation back
0051 line_prefix = '\n-> '   # Probably a better default
0052 
0053 class Pdb(bdb.Bdb, cmd.Cmd):
0054 
0055     def __init__(self):
0056         bdb.Bdb.__init__(self)
0057         cmd.Cmd.__init__(self)
0058         self.prompt = '(Pdb) '
0059         self.aliases = {}
0060         self.mainpyfile = ''
0061         self._wait_for_mainpyfile = 0
0062         # Try to load readline if it exists
0063         try:
0064             import readline
0065         except ImportError:
0066             pass
0067 
0068         # Read $HOME/.pdbrc and ./.pdbrc
0069         self.rcLines = []
0070         if 'HOME' in os.environ:
0071             envHome = os.environ['HOME']
0072             try:
0073                 rcFile = open(os.path.join(envHome, ".pdbrc"))
0074             except IOError:
0075                 pass
0076             else:
0077                 for line in rcFile.readlines():
0078                     self.rcLines.append(line)
0079                 rcFile.close()
0080         try:
0081             rcFile = open(".pdbrc")
0082         except IOError:
0083             pass
0084         else:
0085             for line in rcFile.readlines():
0086                 self.rcLines.append(line)
0087             rcFile.close()
0088 
0089     def reset(self):
0090         bdb.Bdb.reset(self)
0091         self.forget()
0092 
0093     def forget(self):
0094         self.lineno = None
0095         self.stack = []
0096         self.curindex = 0
0097         self.curframe = None
0098 
0099     def setup(self, f, t):
0100         self.forget()
0101         self.stack, self.curindex = self.get_stack(f, t)
0102         self.curframe = self.stack[self.curindex][0]
0103         self.execRcLines()
0104 
0105     # Can be executed earlier than 'setup' if desired
0106     def execRcLines(self):
0107         if self.rcLines:
0108             # Make local copy because of recursion
0109             rcLines = self.rcLines
0110             # executed only once
0111             self.rcLines = []
0112             for line in rcLines:
0113                 line = line[:-1]
0114                 if len(line) > 0 and line[0] != '#':
0115                     self.onecmd(line)
0116 
0117     # Override Bdb methods
0118 
0119     def user_call(self, frame, argument_list):
0120         """This method is called when there is the remote possibility
0121         that we ever need to stop in this function."""
0122         if self._wait_for_mainpyfile:
0123             return
0124         if self.stop_here(frame):
0125             print '--Call--'
0126             self.interaction(frame, None)
0127 
0128     def user_line(self, frame):
0129         """This function is called when we stop or break at this line."""
0130         if self._wait_for_mainpyfile:
0131             if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
0132                 or frame.f_lineno<= 0):
0133                 return
0134             self._wait_for_mainpyfile = 0
0135         self.interaction(frame, None)
0136 
0137     def user_return(self, frame, return_value):
0138         """This function is called when a return trap is set here."""
0139         frame.f_locals['__return__'] = return_value
0140         print '--Return--'
0141         self.interaction(frame, None)
0142 
0143     def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
0144         """This function is called if an exception occurs,
0145         but only if we are to stop at or just below this level."""
0146         frame.f_locals['__exception__'] = exc_type, exc_value
0147         if type(exc_type) == type(''):
0148             exc_type_name = exc_type
0149         else: exc_type_name = exc_type.__name__
0150         print exc_type_name + ':', _saferepr(exc_value)
0151         self.interaction(frame, exc_traceback)
0152 
0153     # General interaction function
0154 
0155     def interaction(self, frame, traceback):
0156         self.setup(frame, traceback)
0157         self.print_stack_entry(self.stack[self.curindex])
0158         self.cmdloop()
0159         self.forget()
0160 
0161     def default(self, line):
0162         if line[:1] == '!': line = line[1:]
0163         locals = self.curframe.f_locals
0164         globals = self.curframe.f_globals
0165         try:
0166             code = compile(line + '\n', '<stdin>', 'single')
0167             exec code in globals, locals
0168         except:
0169             t, v = sys.exc_info()[:2]
0170             if type(t) == type(''):
0171                 exc_type_name = t
0172             else: exc_type_name = t.__name__
0173             print '***', exc_type_name + ':', v
0174 
0175     def precmd(self, line):
0176         """Handle alias expansion and ';;' separator."""
0177         if not line.strip():
0178             return line
0179         args = line.split()
0180         while args[0] in self.aliases:
0181             line = self.aliases[args[0]]
0182             ii = 1
0183             for tmpArg in args[1:]:
0184                 line = line.replace("%" + str(ii),
0185                                       tmpArg)
0186                 ii = ii + 1
0187             line = line.replace("%*", ' '.join(args[1:]))
0188             args = line.split()
0189         # split into ';;' separated commands
0190         # unless it's an alias command
0191         if args[0] != 'alias':
0192             marker = line.find(';;')
0193             if marker >= 0:
0194                 # queue up everything after marker
0195                 next = line[marker+2:].lstrip()
0196                 self.cmdqueue.append(next)
0197                 line = line[:marker].rstrip()
0198         return line
0199 
0200     # Command definitions, called by cmdloop()
0201     # The argument is the remaining string on the command line
0202     # Return true to exit from the command loop
0203 
0204     do_h = cmd.Cmd.do_help
0205 
0206     def do_break(self, arg, temporary = 0):
0207         # break [ ([filename:]lineno | function) [, "condition"] ]
0208         if not arg:
0209             if self.breaks:  # There's at least one
0210                 print "Num Type         Disp Enb   Where"
0211                 for bp in bdb.Breakpoint.bpbynumber:
0212                     if bp:
0213                         bp.bpprint()
0214             return
0215         # parse arguments; comma has lowest precedence
0216         # and cannot occur in filename
0217         filename = None
0218         lineno = None
0219         cond = None
0220         comma = arg.find(',')
0221         if comma > 0:
0222             # parse stuff after comma: "condition"
0223             cond = arg[comma+1:].lstrip()
0224             arg = arg[:comma].rstrip()
0225         # parse stuff before comma: [filename:]lineno | function
0226         colon = arg.rfind(':')
0227         funcname = None
0228         if colon >= 0:
0229             filename = arg[:colon].rstrip()
0230             f = self.lookupmodule(filename)
0231             if not f:
0232                 print '*** ', repr(filename),
0233                 print 'not found from sys.path'
0234                 return
0235             else:
0236                 filename = f
0237             arg = arg[colon+1:].lstrip()
0238             try:
0239                 lineno = int(arg)
0240             except ValueError, msg:
0241                 print '*** Bad lineno:', arg
0242                 return
0243         else:
0244             # no colon; can be lineno or function
0245             try:
0246                 lineno = int(arg)
0247             except ValueError:
0248                 try:
0249                     func = eval(arg,
0250                                 self.curframe.f_globals,
0251                                 self.curframe.f_locals)
0252                 except:
0253                     func = arg
0254                 try:
0255                     if hasattr(func, 'im_func'):
0256                         func = func.im_func
0257                     code = func.func_code
0258                     #use co_name to identify the bkpt (function names
0259                     #could be aliased, but co_name is invariant)
0260                     funcname = code.co_name
0261                     lineno = code.co_firstlineno
0262                     filename = code.co_filename
0263                 except:
0264                     # last thing to try
0265                     (ok, filename, ln) = self.lineinfo(arg)
0266                     if not ok:
0267                         print '*** The specified object',
0268                         print repr(arg),
0269                         print 'is not a function'
0270                         print ('or was not found '
0271                                'along sys.path.')
0272                         return
0273                     funcname = ok # ok contains a function name
0274                     lineno = int(ln)
0275         if not filename:
0276             filename = self.defaultFile()
0277         # Check for reasonable breakpoint
0278         line = self.checkline(filename, lineno)
0279         if line:
0280             # now set the break point
0281             err = self.set_break(filename, line, temporary, cond, funcname)
0282             if err: print '***', err
0283             else:
0284                 bp = self.get_breaks(filename, line)[-1]
0285                 print "Breakpoint %d at %s:%d" % (bp.number,
0286                                                   bp.file,
0287                                                   bp.line)
0288 
0289     # To be overridden in derived debuggers
0290     def defaultFile(self):
0291         """Produce a reasonable default."""
0292         filename = self.curframe.f_code.co_filename
0293         if filename == '<string>' and self.mainpyfile:
0294             filename = self.mainpyfile
0295         return filename
0296 
0297     do_b = do_break
0298 
0299     def do_tbreak(self, arg):
0300         self.do_break(arg, 1)
0301 
0302     def lineinfo(self, identifier):
0303         failed = (None, None, None)
0304         # Input is identifier, may be in single quotes
0305         idstring = identifier.split("'")
0306         if len(idstring) == 1:
0307             # not in single quotes
0308             id = idstring[0].strip()
0309         elif len(idstring) == 3:
0310             # quoted
0311             id = idstring[1].strip()
0312         else:
0313             return failed
0314         if id == '': return failed
0315         parts = id.split('.')
0316         # Protection for derived debuggers
0317         if parts[0] == 'self':
0318             del parts[0]
0319             if len(parts) == 0:
0320                 return failed
0321         # Best first guess at file to look at
0322         fname = self.defaultFile()
0323         if len(parts) == 1:
0324             item = parts[0]
0325         else:
0326             # More than one part.
0327             # First is module, second is method/class
0328             f = self.lookupmodule(parts[0])
0329             if f:
0330                 fname = f
0331             item = parts[1]
0332         answer = find_function(item, fname)
0333         return answer or failed
0334 
0335     def checkline(self, filename, lineno):
0336         """Check whether specified line seems to be executable.
0337 
0338         Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
0339         line or EOF). Warning: testing is not comprehensive.
0340         """
0341         line = linecache.getline(filename, lineno)
0342         if not line:
0343             print 'End of file'
0344             return 0
0345         line = line.strip()
0346         # Don't allow setting breakpoint at a blank line
0347         if (not line or (line[0] == '#') or
0348              (line[:3] == '"""') or line[:3] == "'''"):
0349             print '*** Blank or comment'
0350             return 0
0351         return lineno
0352 
0353     def do_enable(self, arg):
0354         args = arg.split()
0355         for i in args:
0356             try:
0357                 i = int(i)
0358             except ValueError:
0359                 print 'Breakpoint index %r is not a number' % i
0360                 continue
0361 
0362             if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
0363                 print 'No breakpoint numbered', i
0364                 continue
0365 
0366             bp = bdb.Breakpoint.bpbynumber[i]
0367             if bp:
0368                 bp.enable()
0369 
0370     def do_disable(self, arg):
0371         args = arg.split()
0372         for i in args:
0373             try:
0374                 i = int(i)
0375             except ValueError:
0376                 print 'Breakpoint index %r is not a number' % i
0377                 continue
0378 
0379             if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
0380                 print 'No breakpoint numbered', i
0381                 continue
0382 
0383             bp = bdb.Breakpoint.bpbynumber[i]
0384             if bp:
0385                 bp.disable()
0386 
0387     def do_condition(self, arg):
0388         # arg is breakpoint number and condition
0389         args = arg.split(' ', 1)
0390         bpnum = int(args[0].strip())
0391         try:
0392             cond = args[1]
0393         except:
0394             cond = None
0395         bp = bdb.Breakpoint.bpbynumber[bpnum]
0396         if bp:
0397             bp.cond = cond
0398             if not cond:
0399                 print 'Breakpoint', bpnum,
0400                 print 'is now unconditional.'
0401 
0402     def do_ignore(self,arg):
0403         """arg is bp number followed by ignore count."""
0404         args = arg.split()
0405         bpnum = int(args[0].strip())
0406         try:
0407             count = int(args[1].strip())
0408         except:
0409             count = 0
0410         bp = bdb.Breakpoint.bpbynumber[bpnum]
0411         if bp:
0412             bp.ignore = count
0413             if count > 0:
0414                 reply = 'Will ignore next '
0415                 if count > 1:
0416                     reply = reply + '%d crossings' % count
0417                 else:
0418                     reply = reply + '1 crossing'
0419                 print reply + ' of breakpoint %d.' % bpnum
0420             else:
0421                 print 'Will stop next time breakpoint',
0422                 print bpnum, 'is reached.'
0423 
0424     def do_clear(self, arg):
0425         """Three possibilities, tried in this order:
0426         clear -> clear all breaks, ask for confirmation
0427         clear file:lineno -> clear all breaks at file:lineno
0428         clear bpno bpno ... -> clear breakpoints by number"""
0429         if not arg:
0430             try:
0431                 reply = raw_input('Clear all breaks? ')
0432             except EOFError:
0433                 reply = 'no'
0434             reply = reply.strip().lower()
0435             if reply in ('y', 'yes'):
0436                 self.clear_all_breaks()
0437             return
0438         if ':' in arg:
0439             # Make sure it works for "clear C:\foo\bar.py:12"
0440             i = arg.rfind(':')
0441             filename = arg[:i]
0442             arg = arg[i+1:]
0443             try:
0444                 lineno = int(arg)
0445             except:
0446                 err = "Invalid line number (%s)" % arg
0447             else:
0448                 err = self.clear_break(filename, lineno)
0449             if err: print '***', err
0450             return
0451         numberlist = arg.split()
0452         for i in numberlist:
0453             err = self.clear_bpbynumber(i)
0454             if err:
0455                 print '***', err
0456             else:
0457                 print 'Deleted breakpoint %s ' % (i,)
0458     do_cl = do_clear # 'c' is already an abbreviation for 'continue'
0459 
0460     def do_where(self, arg):
0461         self.print_stack_trace()
0462     do_w = do_where
0463     do_bt = do_where
0464 
0465     def do_up(self, arg):
0466         if self.curindex == 0:
0467             print '*** Oldest frame'
0468         else:
0469             self.curindex = self.curindex - 1
0470             self.curframe = self.stack[self.curindex][0]
0471             self.print_stack_entry(self.stack[self.curindex])
0472             self.lineno = None
0473     do_u = do_up
0474 
0475     def do_down(self, arg):
0476         if self.curindex + 1 == len(self.stack):
0477             print '*** Newest frame'
0478         else:
0479             self.curindex = self.curindex + 1
0480             self.curframe = self.stack[self.curindex][0]
0481             self.print_stack_entry(self.stack[self.curindex])
0482             self.lineno = None
0483     do_d = do_down
0484 
0485     def do_step(self, arg):
0486         self.set_step()
0487         return 1
0488     do_s = do_step
0489 
0490     def do_next(self, arg):
0491         self.set_next(self.curframe)
0492         return 1
0493     do_n = do_next
0494 
0495     def do_return(self, arg):
0496         self.set_return(self.curframe)
0497         return 1
0498     do_r = do_return
0499 
0500     def do_continue(self, arg):
0501         self.set_continue()
0502         return 1
0503     do_c = do_cont = do_continue
0504 
0505     def do_jump(self, arg):
0506         if self.curindex + 1 != len(self.stack):
0507             print "*** You can only jump within the bottom frame"
0508             return
0509         try:
0510             arg = int(arg)
0511         except ValueError:
0512             print "*** The 'jump' command requires a line number."
0513         else:
0514             try:
0515                 # Do the jump, fix up our copy of the stack, and display the
0516                 # new position
0517                 self.curframe.f_lineno = arg
0518                 self.stack[self.curindex] = self.stack[self.curindex][0], arg
0519                 self.print_stack_entry(self.stack[self.curindex])
0520             except ValueError, e:
0521                 print '*** Jump failed:', e
0522     do_j = do_jump
0523 
0524     def do_debug(self, arg):
0525         sys.settrace(None)
0526         globals = self.curframe.f_globals
0527         locals = self.curframe.f_locals
0528         p = Pdb()
0529         p.prompt = "(%s) " % self.prompt.strip()
0530         print "ENTERING RECURSIVE DEBUGGER"
0531         sys.call_tracing(p.run, (arg, globals, locals))
0532         print "LEAVING RECURSIVE DEBUGGER"
0533         sys.settrace(self.trace_dispatch)
0534         self.lastcmd = p.lastcmd
0535 
0536     def do_quit(self, arg):
0537         self._user_requested_quit = 1
0538         self.set_quit()
0539         return 1
0540 
0541     do_q = do_quit
0542     do_exit = do_quit
0543 
0544     def do_EOF(self, arg):
0545         print
0546         self._user_requested_quit = 1
0547         self.set_quit()
0548         return 1
0549 
0550     def do_args(self, arg):
0551         f = self.curframe
0552         co = f.f_code
0553         dict = f.f_locals
0554         n = co.co_argcount
0555         if co.co_flags & 4: n = n+1
0556         if co.co_flags & 8: n = n+1
0557         for i in range(n):
0558             name = co.co_varnames[i]
0559             print name, '=',
0560             if name in dict: print dict[name]
0561             else: print "*** undefined ***"
0562     do_a = do_args
0563 
0564     def do_retval(self, arg):
0565         if '__return__' in self.curframe.f_locals:
0566             print self.curframe.f_locals['__return__']
0567         else:
0568             print '*** Not yet returned!'
0569     do_rv = do_retval
0570 
0571     def _getval(self, arg):
0572         try:
0573             return eval(arg, self.curframe.f_globals,
0574                         self.curframe.f_locals)
0575         except:
0576             t, v = sys.exc_info()[:2]
0577             if isinstance(t, str):
0578                 exc_type_name = t
0579             else: exc_type_name = t.__name__
0580             print '***', exc_type_name + ':', repr(v)
0581             raise
0582 
0583     def do_p(self, arg):
0584         try:
0585             print repr(self._getval(arg))
0586         except:
0587             pass
0588 
0589     def do_pp(self, arg):
0590         try:
0591             pprint.pprint(self._getval(arg))
0592         except:
0593             pass
0594 
0595     def do_list(self, arg):
0596         self.lastcmd = 'list'
0597         last = None
0598         if arg:
0599             try:
0600                 x = eval(arg, {}, {})
0601                 if type(x) == type(()):
0602                     first, last = x
0603                     first = int(first)
0604                     last = int(last)
0605                     if last < first:
0606                         # Assume it's a count
0607                         last = first + last
0608                 else:
0609                     first = max(1, int(x) - 5)
0610             except:
0611                 print '*** Error in argument:', repr(arg)
0612                 return
0613         elif self.lineno is None:
0614             first = max(1, self.curframe.f_lineno - 5)
0615         else:
0616             first = self.lineno + 1
0617         if last is None:
0618             last = first + 10
0619         filename = self.curframe.f_code.co_filename
0620         breaklist = self.get_file_breaks(filename)
0621         try:
0622             for lineno in range(first, last+1):
0623                 line = linecache.getline(filename, lineno)
0624                 if not line:
0625                     print '[EOF]'
0626                     break
0627                 else:
0628                     s = repr(lineno).rjust(3)
0629                     if len(s) < 4: s = s + ' '
0630                     if lineno in breaklist: s = s + 'B'
0631                     else: s = s + ' '
0632                     if lineno == self.curframe.f_lineno:
0633                         s = s + '->'
0634                     print s + '\t' + line,
0635                     self.lineno = lineno
0636         except KeyboardInterrupt:
0637             pass
0638     do_l = do_list
0639 
0640     def do_whatis(self, arg):
0641         try:
0642             value = eval(arg, self.curframe.f_globals,
0643                             self.curframe.f_locals)
0644         except:
0645             t, v = sys.exc_info()[:2]
0646             if type(t) == type(''):
0647                 exc_type_name = t
0648             else: exc_type_name = t.__name__
0649             print '***', exc_type_name + ':', repr(v)
0650             return
0651         code = None
0652         # Is it a function?
0653         try: code = value.func_code
0654         except: pass
0655         if code:
0656             print 'Function', code.co_name
0657             return
0658         # Is it an instance method?
0659         try: code = value.im_func.func_code
0660         except: pass
0661         if code:
0662             print 'Method', code.co_name
0663             return
0664         # None of the above...
0665         print type(value)
0666 
0667     def do_alias(self, arg):
0668         args = arg.split()
0669         if len(args) == 0:
0670             keys = self.aliases.keys()
0671             keys.sort()
0672             for alias in keys:
0673                 print "%s = %s" % (alias, self.aliases[alias])
0674             return
0675         if args[0] in self.aliases and len(args) == 1:
0676             print "%s = %s" % (args[0], self.aliases[args[0]])
0677         else:
0678             self.aliases[args[0]] = ' '.join(args[1:])
0679 
0680     def do_unalias(self, arg):
0681         args = arg.split()
0682         if len(args) == 0: return
0683         if args[0] in self.aliases:
0684             del self.aliases[args[0]]
0685 
0686     # Print a traceback starting at the top stack frame.
0687     # The most recently entered frame is printed last;
0688     # this is different from dbx and gdb, but consistent with
0689     # the Python interpreter's stack trace.
0690     # It is also consistent with the up/down commands (which are
0691     # compatible with dbx and gdb: up moves towards 'main()'
0692     # and down moves towards the most recent stack frame).
0693 
0694     def print_stack_trace(self):
0695         try:
0696             for frame_lineno in self.stack:
0697                 self.print_stack_entry(frame_lineno)
0698         except KeyboardInterrupt:
0699             pass
0700 
0701     def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
0702         frame, lineno = frame_lineno
0703         if frame is self.curframe:
0704             print '>',
0705         else:
0706             print ' ',
0707         print self.format_stack_entry(frame_lineno, prompt_prefix)
0708 
0709 
0710     # Help methods (derived from pdb.doc)
0711 
0712     def help_help(self):
0713         self.help_h()
0714 
0715     def help_h(self):
0716         print """h(elp)
0717 Without argument, print the list of available commands.
0718 With a command name as argument, print help about that command
0719 "help pdb" pipes the full documentation file to the $PAGER
0720 "help exec" gives help on the ! command"""
0721 
0722     def help_where(self):
0723         self.help_w()
0724 
0725     def help_w(self):
0726         print """w(here)
0727 Print a stack trace, with the most recent frame at the bottom.
0728 An arrow indicates the "current frame", which determines the
0729 context of most commands.  'bt' is an alias for this command."""
0730 
0731     help_bt = help_w
0732 
0733     def help_down(self):
0734         self.help_d()
0735 
0736     def help_d(self):
0737         print """d(own)
0738 Move the current frame one level down in the stack trace
0739 (to a newer frame)."""
0740 
0741     def help_up(self):
0742         self.help_u()
0743 
0744     def help_u(self):
0745         print """u(p)
0746 Move the current frame one level up in the stack trace
0747 (to an older frame)."""
0748 
0749     def help_break(self):
0750         self.help_b()
0751 
0752     def help_b(self):
0753         print """b(reak) ([file:]lineno | function) [, condition]
0754 With a line number argument, set a break there in the current
0755 file.  With a function name, set a break at first executable line
0756 of that function.  Without argument, list all breaks.  If a second
0757 argument is present, it is a string specifying an expression
0758 which must evaluate to true before the breakpoint is honored.
0759 
0760 The line number may be prefixed with a filename and a colon,
0761 to specify a breakpoint in another file (probably one that
0762 hasn't been loaded yet).  The file is searched for on sys.path;
0763 the .py suffix may be omitted."""
0764 
0765     def help_clear(self):
0766         self.help_cl()
0767 
0768     def help_cl(self):
0769         print "cl(ear) filename:lineno"
0770         print """cl(ear) [bpnumber [bpnumber...]]
0771 With a space separated list of breakpoint numbers, clear
0772 those breakpoints.  Without argument, clear all breaks (but
0773 first ask confirmation).  With a filename:lineno argument,
0774 clear all breaks at that line in that file.
0775 
0776 Note that the argument is different from previous versions of
0777 the debugger (in python distributions 1.5.1 and before) where
0778 a linenumber was used instead of either filename:lineno or
0779 breakpoint numbers."""
0780 
0781     def help_tbreak(self):
0782         print """tbreak  same arguments as break, but breakpoint is
0783 removed when first hit."""
0784 
0785     def help_enable(self):
0786         print """enable bpnumber [bpnumber ...]
0787 Enables the breakpoints given as a space separated list of
0788 bp numbers."""
0789 
0790     def help_disable(self):
0791         print """disable bpnumber [bpnumber ...]
0792 Disables the breakpoints given as a space separated list of
0793 bp numbers."""
0794 
0795     def help_ignore(self):
0796         print """ignore bpnumber count
0797 Sets the ignore count for the given breakpoint number.  A breakpoint
0798 becomes active when the ignore count is zero.  When non-zero, the
0799 count is decremented each time the breakpoint is reached and the
0800 breakpoint is not disabled and any associated condition evaluates
0801 to true."""
0802 
0803     def help_condition(self):
0804         print """condition bpnumber str_condition
0805 str_condition is a string specifying an expression which
0806 must evaluate to true before the breakpoint is honored.
0807 If str_condition is absent, any existing condition is removed;
0808 i.e., the breakpoint is made unconditional."""
0809 
0810     def help_step(self):
0811         self.help_s()
0812 
0813     def help_s(self):
0814         print """s(tep)
0815 Execute the current line, stop at the first possible occasion
0816 (either in a function that is called or in the current function)."""
0817 
0818     def help_next(self):
0819         self.help_n()
0820 
0821     def help_n(self):
0822         print """n(ext)
0823 Continue execution until the next line in the current function
0824 is reached or it returns."""
0825 
0826     def help_return(self):
0827         self.help_r()
0828 
0829     def help_r(self):
0830         print """r(eturn)
0831 Continue execution until the current function returns."""
0832 
0833     def help_continue(self):
0834         self.help_c()
0835 
0836     def help_cont(self):
0837         self.help_c()
0838 
0839     def help_c(self):
0840         print """c(ont(inue))
0841 Continue execution, only stop when a breakpoint is encountered."""
0842 
0843     def help_jump(self):
0844         self.help_j()
0845 
0846     def help_j(self):
0847         print """j(ump) lineno
0848 Set the next line that will be executed."""
0849 
0850     def help_debug(self):
0851         print """debug code
0852 Enter a recursive debugger that steps through the code argument
0853 (which is an arbitrary expression or statement to be executed
0854 in the current environment)."""
0855 
0856     def help_list(self):
0857         self.help_l()
0858 
0859     def help_l(self):
0860         print """l(ist) [first [,last]]
0861 List source code for the current file.
0862 Without arguments, list 11 lines around the current line
0863 or continue the previous listing.
0864 With one argument, list 11 lines starting at that line.
0865 With two arguments, list the given range;
0866 if the second argument is less than the first, it is a count."""
0867 
0868     def help_args(self):
0869         self.help_a()
0870 
0871     def help_a(self):
0872         print """a(rgs)
0873 Print the arguments of the current function."""
0874 
0875     def help_p(self):
0876         print """p expression
0877 Print the value of the expression."""
0878 
0879     def help_pp(self):
0880         print """pp expression
0881 Pretty-print the value of the expression."""
0882 
0883     def help_exec(self):
0884         print """(!) statement
0885 Execute the (one-line) statement in the context of
0886 the current stack frame.
0887 The exclamation point can be omitted unless the first word
0888 of the statement resembles a debugger command.
0889 To assign to a global variable you must always prefix the
0890 command with a 'global' command, e.g.:
0891 (Pdb) global list_options; list_options = ['-l']
0892 (Pdb)"""
0893 
0894     def help_quit(self):
0895         self.help_q()
0896 
0897     def help_q(self):
0898         print """q(uit) or exit - Quit from the debugger.
0899 The program being executed is aborted."""
0900 
0901     help_exit = help_q
0902 
0903     def help_whatis(self):
0904         print """whatis arg
0905 Prints the type of the argument."""
0906 
0907     def help_EOF(self):
0908         print """EOF
0909 Handles the receipt of EOF as a command."""
0910 
0911     def help_alias(self):
0912         print """alias [name [command [parameter parameter ...] ]]
0913 Creates an alias called 'name' the executes 'command'.  The command
0914 must *not* be enclosed in quotes.  Replaceable parameters are
0915 indicated by %1, %2, and so on, while %* is replaced by all the
0916 parameters.  If no command is given, the current alias for name
0917 is shown. If no name is given, all aliases are listed.
0918 
0919 Aliases may be nested and can contain anything that can be
0920 legally typed at the pdb prompt.  Note!  You *can* override
0921 internal pdb commands with aliases!  Those internal commands
0922 are then hidden until the alias is removed.  Aliasing is recursively
0923 applied to the first word of the command line; all other words
0924 in the line are left alone.
0925 
0926 Some useful aliases (especially when placed in the .pdbrc file) are:
0927 
0928 #Print instance variables (usage "pi classInst")
0929 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
0930 
0931 #Print instance variables in self
0932 alias ps pi self
0933 """
0934 
0935     def help_unalias(self):
0936         print """unalias name
0937 Deletes the specified alias."""
0938 
0939     def help_pdb(self):
0940         help()
0941 
0942     def lookupmodule(self, filename):
0943         """Helper function for break/clear parsing -- may be overridden.
0944 
0945         lookupmodule() translates (possibly incomplete) file or module name
0946         into an absolute file name.
0947         """
0948         if os.path.isabs(filename) and  os.path.exists(filename):
0949             return filename
0950         f = os.path.join(sys.path[0], filename)
0951         if  os.path.exists(f) and self.canonic(f) == self.mainpyfile:
0952             return f
0953         root, ext = os.path.splitext(filename)
0954         if ext == '':
0955             filename = filename + '.py'
0956         if os.path.isabs(filename):
0957             return filename
0958         for dirname in sys.path:
0959             while os.path.islink(dirname):
0960                 dirname = os.readlink(dirname)
0961             fullname = os.path.join(dirname, filename)
0962             if os.path.exists(fullname):
0963                 return fullname
0964         return None
0965 
0966     def _runscript(self, filename):
0967         # Start with fresh empty copy of globals and locals and tell the script
0968         # that it's being run as __main__ to avoid scripts being able to access
0969         # the pdb.py namespace.
0970         globals_ = {"__name__" : "__main__"}
0971         locals_ = globals_
0972 
0973         # When bdb sets tracing, a number of call and line events happens
0974         # BEFORE debugger even reaches user's code (and the exact sequence of
0975         # events depends on python version). So we take special measures to
0976         # avoid stopping before we reach the main script (see user_line and
0977         # user_call for details).
0978         self._wait_for_mainpyfile = 1
0979         self.mainpyfile = self.canonic(filename)
0980         self._user_requested_quit = 0
0981         statement = 'execfile( "%s")' % filename
0982         self.run(statement, globals=globals_, locals=locals_)
0983 
0984 # Simplified interface
0985 
0986 def run(statement, globals=None, locals=None):
0987     Pdb().run(statement, globals, locals)
0988 
0989 def runeval(expression, globals=None, locals=None):
0990     return Pdb().runeval(expression, globals, locals)
0991 
0992 def runctx(statement, globals, locals):
0993     # B/W compatibility
0994     run(statement, globals, locals)
0995 
0996 def runcall(*args, **kwds):
0997     return Pdb().runcall(*args, **kwds)
0998 
0999 def set_trace():
1000     Pdb().set_trace()
1001 
1002 # Post-Mortem interface
1003 
1004 def post_mortem(t):
1005     p = Pdb()
1006     p.reset()
1007     while t.tb_next is not None:
1008         t = t.tb_next
1009     p.interaction(t.tb_frame, t)
1010 
1011 def pm():
1012     post_mortem(sys.last_traceback)
1013 
1014 
1015 # Main program for testing
1016 
1017 TESTCMD = 'import x; x.main()'
1018 
1019 def test():
1020     run(TESTCMD)
1021 
1022 # print help
1023 def help():
1024     for dirname in sys.path:
1025         fullname = os.path.join(dirname, 'pdb.doc')
1026         if os.path.exists(fullname):
1027             sts = os.system('${PAGER-more} '+fullname)
1028             if sts: print '*** Pager exit status:', sts
1029             break
1030     else:
1031         print 'Sorry, can\'t find the help file "pdb.doc"',
1032         print 'along the Python search path'
1033 
1034 def main():
1035     if not sys.argv[1:]:
1036         print "usage: pdb.py scriptfile [arg] ..."
1037         sys.exit(2)
1038 
1039     mainpyfile =  sys.argv[1]     # Get script filename
1040     if not os.path.exists(mainpyfile):
1041         print 'Error:', mainpyfile, 'does not exist'
1042         sys.exit(1)
1043 
1044     del sys.argv[0]         # Hide "pdb.py" from argument list
1045 
1046     # Replace pdb's dir with script's dir in front of module search path.
1047     sys.path[0] = os.path.dirname(mainpyfile)
1048 
1049     # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1050     # modified by the script being debugged. It's a bad idea when it was
1051     # changed by the user from the command line. The best approach would be to
1052     # have a "restart" command which would allow explicit specification of
1053     # command line arguments.
1054     pdb = Pdb()
1055     while 1:
1056         try:
1057             pdb._runscript(mainpyfile)
1058             if pdb._user_requested_quit:
1059                 break
1060             print "The program finished and will be restarted"
1061         except SystemExit:
1062             # In most cases SystemExit does not warrant a post-mortem session.
1063             print "The program exited via sys.exit(). Exit status: ",
1064             print sys.exc_info()[1]
1065         except:
1066             traceback.print_exc()
1067             print "Uncaught exception. Entering post mortem debugging"
1068             print "Running 'cont' or 'step' will restart the program"
1069             t = sys.exc_info()[2]
1070             while t.tb_next is not None:
1071                 t = t.tb_next
1072             pdb.interaction(t.tb_frame,t)
1073             print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
1074 
1075 
1076 # When invoked as main program, invoke the debugger on a script
1077 if __name__=='__main__':
1078     main()
1079 

Generated by PyXR 0.9.4
SourceForge.net Logo