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