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