Fix the tag.
[python/dscho.git] / Lib / pdb.py
bloba6355ec116acc38dc466272db30d3578d0a3cd02
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('--Call--', file=self.stdout)
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('--Return--', file=self.stdout)
176 self.interaction(frame, None)
178 def user_exception(self, frame, exc_info):
179 """This function is called if an exception occurs,
180 but only if we are to stop at or just below this level."""
181 exc_type, exc_value, exc_traceback = exc_info
182 frame.f_locals['__exception__'] = exc_type, exc_value
183 exc_type_name = exc_type.__name__
184 print(exc_type_name + ':', _saferepr(exc_value), file=self.stdout)
185 self.interaction(frame, exc_traceback)
187 # General interaction function
189 def interaction(self, frame, traceback):
190 self.setup(frame, traceback)
191 self.print_stack_entry(self.stack[self.curindex])
192 self.cmdloop()
193 self.forget()
195 def default(self, line):
196 if line[:1] == '!': line = line[1:]
197 locals = self.curframe.f_locals
198 globals = self.curframe.f_globals
199 try:
200 code = compile(line + '\n', '<stdin>', 'single')
201 save_stdout = sys.stdout
202 save_stdin = sys.stdin
203 try:
204 sys.stdin = self.stdin
205 sys.stdout = self.stdout
206 exec(code, globals, locals)
207 finally:
208 sys.stdout = save_stdout
209 sys.stdin = save_stdin
210 except:
211 t, v = sys.exc_info()[:2]
212 if type(t) == type(''):
213 exc_type_name = t
214 else: exc_type_name = t.__name__
215 print('***', exc_type_name + ':', v, file=self.stdout)
217 def precmd(self, line):
218 """Handle alias expansion and ';;' separator."""
219 if not line.strip():
220 return line
221 args = line.split()
222 while args[0] in self.aliases:
223 line = self.aliases[args[0]]
224 ii = 1
225 for tmpArg in args[1:]:
226 line = line.replace("%" + str(ii),
227 tmpArg)
228 ii = ii + 1
229 line = line.replace("%*", ' '.join(args[1:]))
230 args = line.split()
231 # split into ';;' separated commands
232 # unless it's an alias command
233 if args[0] != 'alias':
234 marker = line.find(';;')
235 if marker >= 0:
236 # queue up everything after marker
237 next = line[marker+2:].lstrip()
238 self.cmdqueue.append(next)
239 line = line[:marker].rstrip()
240 return line
242 def onecmd(self, line):
243 """Interpret the argument as though it had been typed in response
244 to the prompt.
246 Checks whether this line is typed at the normal prompt or in
247 a breakpoint command list definition.
249 if not self.commands_defining:
250 return cmd.Cmd.onecmd(self, line)
251 else:
252 return self.handle_command_def(line)
254 def handle_command_def(self,line):
255 """ Handles one command line during command list definition. """
256 cmd, arg, line = self.parseline(line)
257 if cmd == 'silent':
258 self.commands_silent[self.commands_bnum] = True
259 return # continue to handle other cmd def in the cmd list
260 elif cmd == 'end':
261 self.cmdqueue = []
262 return 1 # end of cmd list
263 cmdlist = self.commands[self.commands_bnum]
264 if (arg):
265 cmdlist.append(cmd+' '+arg)
266 else:
267 cmdlist.append(cmd)
268 # Determine if we must stop
269 try:
270 func = getattr(self, 'do_' + cmd)
271 except AttributeError:
272 func = self.default
273 if func.__name__ in self.commands_resuming : # one of the resuming commands.
274 self.commands_doprompt[self.commands_bnum] = False
275 self.cmdqueue = []
276 return 1
277 return
279 # Command definitions, called by cmdloop()
280 # The argument is the remaining string on the command line
281 # Return true to exit from the command loop
283 do_h = cmd.Cmd.do_help
285 def do_commands(self, arg):
286 """Defines a list of commands associated to a breakpoint
287 Those commands will be executed whenever the breakpoint causes the program to stop execution."""
288 if not arg:
289 bnum = len(bdb.Breakpoint.bpbynumber)-1
290 else:
291 try:
292 bnum = int(arg)
293 except:
294 print("Usage : commands [bnum]\n ...\n end", file=self.stdout)
295 return
296 self.commands_bnum = bnum
297 self.commands[bnum] = []
298 self.commands_doprompt[bnum] = True
299 self.commands_silent[bnum] = False
300 prompt_back = self.prompt
301 self.prompt = '(com) '
302 self.commands_defining = True
303 self.cmdloop()
304 self.commands_defining = False
305 self.prompt = prompt_back
307 def do_break(self, arg, temporary = 0):
308 # break [ ([filename:]lineno | function) [, "condition"] ]
309 if not arg:
310 if self.breaks: # There's at least one
311 print("Num Type Disp Enb Where", file=self.stdout)
312 for bp in bdb.Breakpoint.bpbynumber:
313 if bp:
314 bp.bpprint(self.stdout)
315 return
316 # parse arguments; comma has lowest precedence
317 # and cannot occur in filename
318 filename = None
319 lineno = None
320 cond = None
321 comma = arg.find(',')
322 if comma > 0:
323 # parse stuff after comma: "condition"
324 cond = arg[comma+1:].lstrip()
325 arg = arg[:comma].rstrip()
326 # parse stuff before comma: [filename:]lineno | function
327 colon = arg.rfind(':')
328 funcname = None
329 if colon >= 0:
330 filename = arg[:colon].rstrip()
331 f = self.lookupmodule(filename)
332 if not f:
333 print('*** ', repr(filename), end=' ', file=self.stdout)
334 print('not found from sys.path', file=self.stdout)
335 return
336 else:
337 filename = f
338 arg = arg[colon+1:].lstrip()
339 try:
340 lineno = int(arg)
341 except ValueError as msg:
342 print('*** Bad lineno:', arg, file=self.stdout)
343 return
344 else:
345 # no colon; can be lineno or function
346 try:
347 lineno = int(arg)
348 except ValueError:
349 try:
350 func = eval(arg,
351 self.curframe.f_globals,
352 self.curframe.f_locals)
353 except:
354 func = arg
355 try:
356 if hasattr(func, '__func__'):
357 func = func.__func__
358 code = func.__code__
359 #use co_name to identify the bkpt (function names
360 #could be aliased, but co_name is invariant)
361 funcname = code.co_name
362 lineno = code.co_firstlineno
363 filename = code.co_filename
364 except:
365 # last thing to try
366 (ok, filename, ln) = self.lineinfo(arg)
367 if not ok:
368 print('*** The specified object', end=' ', file=self.stdout)
369 print(repr(arg), end=' ', file=self.stdout)
370 print('is not a function', file=self.stdout)
371 print('or was not found along sys.path.', file=self.stdout)
372 return
373 funcname = ok # ok contains a function name
374 lineno = int(ln)
375 if not filename:
376 filename = self.defaultFile()
377 # Check for reasonable breakpoint
378 line = self.checkline(filename, lineno)
379 if line:
380 # now set the break point
381 err = self.set_break(filename, line, temporary, cond, funcname)
382 if err: print('***', err, file=self.stdout)
383 else:
384 bp = self.get_breaks(filename, line)[-1]
385 print("Breakpoint %d at %s:%d" % (bp.number,
386 bp.file,
387 bp.line), file=self.stdout)
389 # To be overridden in derived debuggers
390 def defaultFile(self):
391 """Produce a reasonable default."""
392 filename = self.curframe.f_code.co_filename
393 if filename == '<string>' and self.mainpyfile:
394 filename = self.mainpyfile
395 return filename
397 do_b = do_break
399 def do_tbreak(self, arg):
400 self.do_break(arg, 1)
402 def lineinfo(self, identifier):
403 failed = (None, None, None)
404 # Input is identifier, may be in single quotes
405 idstring = identifier.split("'")
406 if len(idstring) == 1:
407 # not in single quotes
408 id = idstring[0].strip()
409 elif len(idstring) == 3:
410 # quoted
411 id = idstring[1].strip()
412 else:
413 return failed
414 if id == '': return failed
415 parts = id.split('.')
416 # Protection for derived debuggers
417 if parts[0] == 'self':
418 del parts[0]
419 if len(parts) == 0:
420 return failed
421 # Best first guess at file to look at
422 fname = self.defaultFile()
423 if len(parts) == 1:
424 item = parts[0]
425 else:
426 # More than one part.
427 # First is module, second is method/class
428 f = self.lookupmodule(parts[0])
429 if f:
430 fname = f
431 item = parts[1]
432 answer = find_function(item, fname)
433 return answer or failed
435 def checkline(self, filename, lineno):
436 """Check whether specified line seems to be executable.
438 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
439 line or EOF). Warning: testing is not comprehensive.
441 line = linecache.getline(filename, lineno)
442 if not line:
443 print('End of file', file=self.stdout)
444 return 0
445 line = line.strip()
446 # Don't allow setting breakpoint at a blank line
447 if (not line or (line[0] == '#') or
448 (line[:3] == '"""') or line[:3] == "'''"):
449 print('*** Blank or comment', file=self.stdout)
450 return 0
451 return lineno
453 def do_enable(self, arg):
454 args = arg.split()
455 for i in args:
456 try:
457 i = int(i)
458 except ValueError:
459 print('Breakpoint index %r is not a number' % i, file=self.stdout)
460 continue
462 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
463 print('No breakpoint numbered', i, file=self.stdout)
464 continue
466 bp = bdb.Breakpoint.bpbynumber[i]
467 if bp:
468 bp.enable()
470 def do_disable(self, arg):
471 args = arg.split()
472 for i in args:
473 try:
474 i = int(i)
475 except ValueError:
476 print('Breakpoint index %r is not a number' % i, file=self.stdout)
477 continue
479 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
480 print('No breakpoint numbered', i, file=self.stdout)
481 continue
483 bp = bdb.Breakpoint.bpbynumber[i]
484 if bp:
485 bp.disable()
487 def do_condition(self, arg):
488 # arg is breakpoint number and condition
489 args = arg.split(' ', 1)
490 try:
491 bpnum = int(args[0].strip())
492 except ValueError:
493 # something went wrong
494 print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
495 return
496 try:
497 cond = args[1]
498 except:
499 cond = None
500 try:
501 bp = bdb.Breakpoint.bpbynumber[bpnum]
502 except IndexError:
503 print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
504 return
505 if bp:
506 bp.cond = cond
507 if not cond:
508 print('Breakpoint', bpnum, end=' ', file=self.stdout)
509 print('is now unconditional.', file=self.stdout)
511 def do_ignore(self,arg):
512 """arg is bp number followed by ignore count."""
513 args = arg.split()
514 try:
515 bpnum = int(args[0].strip())
516 except ValueError:
517 # something went wrong
518 print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
519 return
520 try:
521 count = int(args[1].strip())
522 except:
523 count = 0
524 try:
525 bp = bdb.Breakpoint.bpbynumber[bpnum]
526 except IndexError:
527 print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
528 return
529 if bp:
530 bp.ignore = count
531 if count > 0:
532 reply = 'Will ignore next '
533 if count > 1:
534 reply = reply + '%d crossings' % count
535 else:
536 reply = reply + '1 crossing'
537 print(reply + ' of breakpoint %d.' % bpnum, file=self.stdout)
538 else:
539 print('Will stop next time breakpoint', end=' ', file=self.stdout)
540 print(bpnum, 'is reached.', file=self.stdout)
542 def do_clear(self, arg):
543 """Three possibilities, tried in this order:
544 clear -> clear all breaks, ask for confirmation
545 clear file:lineno -> clear all breaks at file:lineno
546 clear bpno bpno ... -> clear breakpoints by number"""
547 if not arg:
548 try:
549 reply = input('Clear all breaks? ')
550 except EOFError:
551 reply = 'no'
552 reply = reply.strip().lower()
553 if reply in ('y', 'yes'):
554 self.clear_all_breaks()
555 return
556 if ':' in arg:
557 # Make sure it works for "clear C:\foo\bar.py:12"
558 i = arg.rfind(':')
559 filename = arg[:i]
560 arg = arg[i+1:]
561 try:
562 lineno = int(arg)
563 except ValueError:
564 err = "Invalid line number (%s)" % arg
565 else:
566 err = self.clear_break(filename, lineno)
567 if err: print('***', err, file=self.stdout)
568 return
569 numberlist = arg.split()
570 for i in numberlist:
571 try:
572 i = int(i)
573 except ValueError:
574 print('Breakpoint index %r is not a number' % i, file=self.stdout)
575 continue
577 if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
578 print('No breakpoint numbered', i, file=self.stdout)
579 continue
580 err = self.clear_bpbynumber(i)
581 if err:
582 print('***', err, file=self.stdout)
583 else:
584 print('Deleted breakpoint', i, file=self.stdout)
585 do_cl = do_clear # 'c' is already an abbreviation for 'continue'
587 def do_where(self, arg):
588 self.print_stack_trace()
589 do_w = do_where
590 do_bt = do_where
592 def do_up(self, arg):
593 if self.curindex == 0:
594 print('*** Oldest frame', file=self.stdout)
595 else:
596 self.curindex = self.curindex - 1
597 self.curframe = self.stack[self.curindex][0]
598 self.print_stack_entry(self.stack[self.curindex])
599 self.lineno = None
600 do_u = do_up
602 def do_down(self, arg):
603 if self.curindex + 1 == len(self.stack):
604 print('*** Newest frame', file=self.stdout)
605 else:
606 self.curindex = self.curindex + 1
607 self.curframe = self.stack[self.curindex][0]
608 self.print_stack_entry(self.stack[self.curindex])
609 self.lineno = None
610 do_d = do_down
612 def do_step(self, arg):
613 self.set_step()
614 return 1
615 do_s = do_step
617 def do_next(self, arg):
618 self.set_next(self.curframe)
619 return 1
620 do_n = do_next
622 def do_run(self, arg):
623 """Restart program by raising an exception to be caught in the main debugger
624 loop. If arguments were given, set them in sys.argv."""
625 if arg:
626 import shlex
627 argv0 = sys.argv[0:1]
628 sys.argv = shlex.split(arg)
629 sys.argv[:0] = argv0
630 raise Restart
632 do_restart = do_run
634 def do_return(self, arg):
635 self.set_return(self.curframe)
636 return 1
637 do_r = do_return
639 def do_continue(self, arg):
640 self.set_continue()
641 return 1
642 do_c = do_cont = do_continue
644 def do_jump(self, arg):
645 if self.curindex + 1 != len(self.stack):
646 print("*** You can only jump within the bottom frame", file=self.stdout)
647 return
648 try:
649 arg = int(arg)
650 except ValueError:
651 print("*** The 'jump' command requires a line number.", file=self.stdout)
652 else:
653 try:
654 # Do the jump, fix up our copy of the stack, and display the
655 # new position
656 self.curframe.f_lineno = arg
657 self.stack[self.curindex] = self.stack[self.curindex][0], arg
658 self.print_stack_entry(self.stack[self.curindex])
659 except ValueError as e:
660 print('*** Jump failed:', e, file=self.stdout)
661 do_j = do_jump
663 def do_debug(self, arg):
664 sys.settrace(None)
665 globals = self.curframe.f_globals
666 locals = self.curframe.f_locals
667 p = Pdb(self.completekey, self.stdin, self.stdout)
668 p.prompt = "(%s) " % self.prompt.strip()
669 print("ENTERING RECURSIVE DEBUGGER", file=self.stdout)
670 sys.call_tracing(p.run, (arg, globals, locals))
671 print("LEAVING RECURSIVE DEBUGGER", file=self.stdout)
672 sys.settrace(self.trace_dispatch)
673 self.lastcmd = p.lastcmd
675 def do_quit(self, arg):
676 self._user_requested_quit = 1
677 self.set_quit()
678 return 1
680 do_q = do_quit
681 do_exit = do_quit
683 def do_EOF(self, arg):
684 print(file=self.stdout)
685 self._user_requested_quit = 1
686 self.set_quit()
687 return 1
689 def do_args(self, arg):
690 f = self.curframe
691 co = f.f_code
692 dict = f.f_locals
693 n = co.co_argcount
694 if co.co_flags & 4: n = n+1
695 if co.co_flags & 8: n = n+1
696 for i in range(n):
697 name = co.co_varnames[i]
698 print(name, '=', end=' ', file=self.stdout)
699 if name in dict: print(dict[name], file=self.stdout)
700 else: print("*** undefined ***", file=self.stdout)
701 do_a = do_args
703 def do_retval(self, arg):
704 if '__return__' in self.curframe.f_locals:
705 print(self.curframe.f_locals['__return__'], file=self.stdout)
706 else:
707 print('*** Not yet returned!', file=self.stdout)
708 do_rv = do_retval
710 def _getval(self, arg):
711 try:
712 return eval(arg, self.curframe.f_globals,
713 self.curframe.f_locals)
714 except:
715 t, v = sys.exc_info()[:2]
716 if isinstance(t, str):
717 exc_type_name = t
718 else: exc_type_name = t.__name__
719 print('***', exc_type_name + ':', repr(v), file=self.stdout)
720 raise
722 def do_p(self, arg):
723 try:
724 print(repr(self._getval(arg)), file=self.stdout)
725 except:
726 pass
727 # make "print" an alias of "p" since print isn't a Python statement anymore
728 do_print = do_p
730 def do_pp(self, arg):
731 try:
732 pprint.pprint(self._getval(arg), self.stdout)
733 except:
734 pass
736 def do_list(self, arg):
737 self.lastcmd = 'list'
738 last = None
739 if arg:
740 try:
741 x = eval(arg, {}, {})
742 if type(x) == type(()):
743 first, last = x
744 first = int(first)
745 last = int(last)
746 if last < first:
747 # Assume it's a count
748 last = first + last
749 else:
750 first = max(1, int(x) - 5)
751 except:
752 print('*** Error in argument:', repr(arg), file=self.stdout)
753 return
754 elif self.lineno is None:
755 first = max(1, self.curframe.f_lineno - 5)
756 else:
757 first = self.lineno + 1
758 if last is None:
759 last = first + 10
760 filename = self.curframe.f_code.co_filename
761 breaklist = self.get_file_breaks(filename)
762 try:
763 for lineno in range(first, last+1):
764 line = linecache.getline(filename, lineno)
765 if not line:
766 print('[EOF]', file=self.stdout)
767 break
768 else:
769 s = repr(lineno).rjust(3)
770 if len(s) < 4: s = s + ' '
771 if lineno in breaklist: s = s + 'B'
772 else: s = s + ' '
773 if lineno == self.curframe.f_lineno:
774 s = s + '->'
775 print(s + '\t' + line, end='', file=self.stdout)
776 self.lineno = lineno
777 except KeyboardInterrupt:
778 pass
779 do_l = do_list
781 def do_whatis(self, arg):
782 try:
783 value = eval(arg, self.curframe.f_globals,
784 self.curframe.f_locals)
785 except:
786 t, v = sys.exc_info()[:2]
787 if type(t) == type(''):
788 exc_type_name = t
789 else: exc_type_name = t.__name__
790 print('***', exc_type_name + ':', repr(v), file=self.stdout)
791 return
792 code = None
793 # Is it a function?
794 try: code = value.__code__
795 except: pass
796 if code:
797 print('Function', code.co_name, file=self.stdout)
798 return
799 # Is it an instance method?
800 try: code = value.__func__.__code__
801 except: pass
802 if code:
803 print('Method', code.co_name, file=self.stdout)
804 return
805 # None of the above...
806 print(type(value), file=self.stdout)
808 def do_alias(self, arg):
809 args = arg.split()
810 if len(args) == 0:
811 keys = self.aliases.keys()
812 keys.sort()
813 for alias in keys:
814 print("%s = %s" % (alias, self.aliases[alias]), file=self.stdout)
815 return
816 if args[0] in self.aliases and len(args) == 1:
817 print("%s = %s" % (args[0], self.aliases[args[0]]), file=self.stdout)
818 else:
819 self.aliases[args[0]] = ' '.join(args[1:])
821 def do_unalias(self, arg):
822 args = arg.split()
823 if len(args) == 0: return
824 if args[0] in self.aliases:
825 del self.aliases[args[0]]
827 #list of all the commands making the program resume execution.
828 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
829 'do_quit', 'do_jump']
831 # Print a traceback starting at the top stack frame.
832 # The most recently entered frame is printed last;
833 # this is different from dbx and gdb, but consistent with
834 # the Python interpreter's stack trace.
835 # It is also consistent with the up/down commands (which are
836 # compatible with dbx and gdb: up moves towards 'main()'
837 # and down moves towards the most recent stack frame).
839 def print_stack_trace(self):
840 try:
841 for frame_lineno in self.stack:
842 self.print_stack_entry(frame_lineno)
843 except KeyboardInterrupt:
844 pass
846 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
847 frame, lineno = frame_lineno
848 if frame is self.curframe:
849 print('>', end=' ', file=self.stdout)
850 else:
851 print(' ', end=' ', file=self.stdout)
852 print(self.format_stack_entry(frame_lineno,
853 prompt_prefix), file=self.stdout)
856 # Help methods (derived from pdb.doc)
858 def help_help(self):
859 self.help_h()
861 def help_h(self):
862 print("""h(elp)
863 Without argument, print the list of available commands.
864 With a command name as argument, print help about that command
865 "help pdb" pipes the full documentation file to the $PAGER
866 "help exec" gives help on the ! command""", file=self.stdout)
868 def help_where(self):
869 self.help_w()
871 def help_w(self):
872 print("""w(here)
873 Print a stack trace, with the most recent frame at the bottom.
874 An arrow indicates the "current frame", which determines the
875 context of most commands. 'bt' is an alias for this command.""", file=self.stdout)
877 help_bt = help_w
879 def help_down(self):
880 self.help_d()
882 def help_d(self):
883 print("""d(own)
884 Move the current frame one level down in the stack trace
885 (to a newer frame).""", file=self.stdout)
887 def help_up(self):
888 self.help_u()
890 def help_u(self):
891 print("""u(p)
892 Move the current frame one level up in the stack trace
893 (to an older frame).""", file=self.stdout)
895 def help_break(self):
896 self.help_b()
898 def help_b(self):
899 print("""b(reak) ([file:]lineno | function) [, condition]
900 With a line number argument, set a break there in the current
901 file. With a function name, set a break at first executable line
902 of that function. Without argument, list all breaks. If a second
903 argument is present, it is a string specifying an expression
904 which must evaluate to true before the breakpoint is honored.
906 The line number may be prefixed with a filename and a colon,
907 to specify a breakpoint in another file (probably one that
908 hasn't been loaded yet). The file is searched for on sys.path;
909 the .py suffix may be omitted.""", file=self.stdout)
911 def help_clear(self):
912 self.help_cl()
914 def help_cl(self):
915 print("cl(ear) filename:lineno", file=self.stdout)
916 print("""cl(ear) [bpnumber [bpnumber...]]
917 With a space separated list of breakpoint numbers, clear
918 those breakpoints. Without argument, clear all breaks (but
919 first ask confirmation). With a filename:lineno argument,
920 clear all breaks at that line in that file.""", file=self.stdout)
922 def help_tbreak(self):
923 print("""tbreak same arguments as break, but breakpoint is
924 removed when first hit.""", file=self.stdout)
926 def help_enable(self):
927 print("""enable bpnumber [bpnumber ...]
928 Enables the breakpoints given as a space separated list of
929 bp numbers.""", file=self.stdout)
931 def help_disable(self):
932 print("""disable bpnumber [bpnumber ...]
933 Disables the breakpoints given as a space separated list of
934 bp numbers.""", file=self.stdout)
936 def help_ignore(self):
937 print("""ignore bpnumber count
938 Sets the ignore count for the given breakpoint number. A breakpoint
939 becomes active when the ignore count is zero. When non-zero, the
940 count is decremented each time the breakpoint is reached and the
941 breakpoint is not disabled and any associated condition evaluates
942 to true.""", file=self.stdout)
944 def help_condition(self):
945 print("""condition bpnumber str_condition
946 str_condition is a string specifying an expression which
947 must evaluate to true before the breakpoint is honored.
948 If str_condition is absent, any existing condition is removed;
949 i.e., the breakpoint is made unconditional.""", file=self.stdout)
951 def help_step(self):
952 self.help_s()
954 def help_s(self):
955 print("""s(tep)
956 Execute the current line, stop at the first possible occasion
957 (either in a function that is called or in the current function).""", file=self.stdout)
959 def help_next(self):
960 self.help_n()
962 def help_n(self):
963 print("""n(ext)
964 Continue execution until the next line in the current function
965 is reached or it returns.""", file=self.stdout)
967 def help_return(self):
968 self.help_r()
970 def help_r(self):
971 print("""r(eturn)
972 Continue execution until the current function returns.""", file=self.stdout)
974 def help_continue(self):
975 self.help_c()
977 def help_cont(self):
978 self.help_c()
980 def help_c(self):
981 print("""c(ont(inue))
982 Continue execution, only stop when a breakpoint is encountered.""", file=self.stdout)
984 def help_jump(self):
985 self.help_j()
987 def help_j(self):
988 print("""j(ump) lineno
989 Set the next line that will be executed.""", file=self.stdout)
991 def help_debug(self):
992 print("""debug code
993 Enter a recursive debugger that steps through the code argument
994 (which is an arbitrary expression or statement to be executed
995 in the current environment).""", file=self.stdout)
997 def help_list(self):
998 self.help_l()
1000 def help_l(self):
1001 print("""l(ist) [first [,last]]
1002 List source code for the current file.
1003 Without arguments, list 11 lines around the current line
1004 or continue the previous listing.
1005 With one argument, list 11 lines starting at that line.
1006 With two arguments, list the given range;
1007 if the second argument is less than the first, it is a count.""", file=self.stdout)
1009 def help_args(self):
1010 self.help_a()
1012 def help_a(self):
1013 print("""a(rgs)
1014 Print the arguments of the current function.""", file=self.stdout)
1016 def help_p(self):
1017 print("""p(rint) expression
1018 Print the value of the expression.""", file=self.stdout)
1020 def help_pp(self):
1021 print("""pp expression
1022 Pretty-print the value of the expression.""", file=self.stdout)
1024 def help_exec(self):
1025 print("""(!) statement
1026 Execute the (one-line) statement in the context of
1027 the current stack frame.
1028 The exclamation point can be omitted unless the first word
1029 of the statement resembles a debugger command.
1030 To assign to a global variable you must always prefix the
1031 command with a 'global' command, e.g.:
1032 (Pdb) global list_options; list_options = ['-l']
1033 (Pdb)""", file=self.stdout)
1035 def help_run(self):
1036 print("""run [args...]
1037 Restart the debugged python program. If a string is supplied, it is
1038 splitted with "shlex" and the result is used as the new sys.argv.
1039 History, breakpoints, actions and debugger options are preserved.
1040 "restart" is an alias for "run".""")
1042 help_restart = help_run
1044 def help_quit(self):
1045 self.help_q()
1047 def help_q(self):
1048 print("""q(uit) or exit - Quit from the debugger.
1049 The program being executed is aborted.""", file=self.stdout)
1051 help_exit = help_q
1053 def help_whatis(self):
1054 print("""whatis arg
1055 Prints the type of the argument.""", file=self.stdout)
1057 def help_EOF(self):
1058 print("""EOF
1059 Handles the receipt of EOF as a command.""", file=self.stdout)
1061 def help_alias(self):
1062 print("""alias [name [command [parameter parameter ...] ]]
1063 Creates an alias called 'name' the executes 'command'. The command
1064 must *not* be enclosed in quotes. Replaceable parameters are
1065 indicated by %1, %2, and so on, while %* is replaced by all the
1066 parameters. If no command is given, the current alias for name
1067 is shown. If no name is given, all aliases are listed.
1069 Aliases may be nested and can contain anything that can be
1070 legally typed at the pdb prompt. Note! You *can* override
1071 internal pdb commands with aliases! Those internal commands
1072 are then hidden until the alias is removed. Aliasing is recursively
1073 applied to the first word of the command line; all other words
1074 in the line are left alone.
1076 Some useful aliases (especially when placed in the .pdbrc file) are:
1078 #Print instance variables (usage "pi classInst")
1079 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
1081 #Print instance variables in self
1082 alias ps pi self
1083 """, file=self.stdout)
1085 def help_unalias(self):
1086 print("""unalias name
1087 Deletes the specified alias.""", file=self.stdout)
1089 def help_commands(self):
1090 print("""commands [bpnumber]
1091 (com) ...
1092 (com) end
1093 (Pdb)
1095 Specify a list of commands for breakpoint number bpnumber. The
1096 commands themselves appear on the following lines. Type a line
1097 containing just 'end' to terminate the commands.
1099 To remove all commands from a breakpoint, type commands and
1100 follow it immediately with end; that is, give no commands.
1102 With no bpnumber argument, commands refers to the last
1103 breakpoint set.
1105 You can use breakpoint commands to start your program up again.
1106 Simply use the continue command, or step, or any other
1107 command that resumes execution.
1109 Specifying any command resuming execution (currently continue,
1110 step, next, return, jump, quit and their abbreviations) terminates
1111 the command list (as if that command was immediately followed by end).
1112 This is because any time you resume execution
1113 (even with a simple next or step), you may encounter
1114 another breakpoint--which could have its own command list, leading to
1115 ambiguities about which list to execute.
1117 If you use the 'silent' command in the command list, the
1118 usual message about stopping at a breakpoint is not printed. This may
1119 be desirable for breakpoints that are to print a specific message and
1120 then continue. If none of the other commands print anything, you
1121 see no sign that the breakpoint was reached.
1122 """, file=self.stdout)
1124 def help_pdb(self):
1125 help()
1127 def lookupmodule(self, filename):
1128 """Helper function for break/clear parsing -- may be overridden.
1130 lookupmodule() translates (possibly incomplete) file or module name
1131 into an absolute file name.
1133 if os.path.isabs(filename) and os.path.exists(filename):
1134 return filename
1135 f = os.path.join(sys.path[0], filename)
1136 if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
1137 return f
1138 root, ext = os.path.splitext(filename)
1139 if ext == '':
1140 filename = filename + '.py'
1141 if os.path.isabs(filename):
1142 return filename
1143 for dirname in sys.path:
1144 while os.path.islink(dirname):
1145 dirname = os.readlink(dirname)
1146 fullname = os.path.join(dirname, filename)
1147 if os.path.exists(fullname):
1148 return fullname
1149 return None
1151 def _runscript(self, filename):
1152 # The script has to run in __main__ namespace (or imports from
1153 # __main__ will break).
1155 # So we clear up the __main__ and set several special variables
1156 # (this gets rid of pdb's globals and cleans old variables on restarts).
1157 import __main__
1158 __main__.__dict__.clear()
1159 __main__.__dict__.update({"__name__" : "__main__",
1160 "__file__" : filename,
1161 "__builtins__": __builtins__,
1164 # When bdb sets tracing, a number of call and line events happens
1165 # BEFORE debugger even reaches user's code (and the exact sequence of
1166 # events depends on python version). So we take special measures to
1167 # avoid stopping before we reach the main script (see user_line and
1168 # user_call for details).
1169 self._wait_for_mainpyfile = 1
1170 self.mainpyfile = self.canonic(filename)
1171 self._user_requested_quit = 0
1172 with open(filename) as fp:
1173 statement = fp.read()
1174 self.run(statement)
1176 # Simplified interface
1178 def run(statement, globals=None, locals=None):
1179 Pdb().run(statement, globals, locals)
1181 def runeval(expression, globals=None, locals=None):
1182 return Pdb().runeval(expression, globals, locals)
1184 def runctx(statement, globals, locals):
1185 # B/W compatibility
1186 run(statement, globals, locals)
1188 def runcall(*args, **kwds):
1189 return Pdb().runcall(*args, **kwds)
1191 def set_trace():
1192 Pdb().set_trace(sys._getframe().f_back)
1194 # Post-Mortem interface
1196 def post_mortem(t=None):
1197 # handling the default
1198 if t is None:
1199 # sys.exc_info() returns (type, value, traceback) if an exception is
1200 # being handled, otherwise it returns None
1201 t = sys.exc_info()[2]
1202 if t is None:
1203 raise ValueError("A valid traceback must be passed if no "
1204 "exception is being handled")
1206 p = Pdb()
1207 p.reset()
1208 while t.tb_next is not None:
1209 t = t.tb_next
1210 p.interaction(t.tb_frame, t)
1212 def pm():
1213 post_mortem(sys.last_traceback)
1216 # Main program for testing
1218 TESTCMD = 'import x; x.main()'
1220 def test():
1221 run(TESTCMD)
1223 # print help
1224 def help():
1225 for dirname in sys.path:
1226 fullname = os.path.join(dirname, 'pdb.doc')
1227 if os.path.exists(fullname):
1228 sts = os.system('${PAGER-more} '+fullname)
1229 if sts: print('*** Pager exit status:', sts)
1230 break
1231 else:
1232 print('Sorry, can\'t find the help file "pdb.doc"', end=' ')
1233 print('along the Python search path')
1235 def main():
1236 if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
1237 print("usage: pdb.py scriptfile [arg] ...")
1238 sys.exit(2)
1240 mainpyfile = sys.argv[1] # Get script filename
1241 if not os.path.exists(mainpyfile):
1242 print('Error:', mainpyfile, 'does not exist')
1243 sys.exit(1)
1245 del sys.argv[0] # Hide "pdb.py" from argument list
1247 # Replace pdb's dir with script's dir in front of module search path.
1248 sys.path[0] = os.path.dirname(mainpyfile)
1250 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1251 # modified by the script being debugged. It's a bad idea when it was
1252 # changed by the user from the command line. There is a "restart" command which
1253 # allows explicit specification of command line arguments.
1254 pdb = Pdb()
1255 while 1:
1256 try:
1257 pdb._runscript(mainpyfile)
1258 if pdb._user_requested_quit:
1259 break
1260 print("The program finished and will be restarted")
1261 except Restart:
1262 print("Restarting", mainpyfile, "with arguments:")
1263 print("\t" + " ".join(sys.argv[1:]))
1264 except SystemExit:
1265 # In most cases SystemExit does not warrant a post-mortem session.
1266 print("The program exited via sys.exit(). Exit status: ", end=' ')
1267 print(sys.exc_info()[1])
1268 except:
1269 traceback.print_exc()
1270 print("Uncaught exception. Entering post mortem debugging")
1271 print("Running 'cont' or 'step' will restart the program")
1272 t = sys.exc_info()[2]
1273 while t.tb_next is not None:
1274 t = t.tb_next
1275 pdb.interaction(t.tb_frame,t)
1276 print("Post mortem debugger finished. The "+mainpyfile+" will be restarted")
1279 # When invoked as main program, invoke the debugger on a script
1280 if __name__ == '__main__':
1281 import pdb
1282 pdb.main()