source: python/vendor/Python-2.6.5/Lib/pdb.py

Last change on this file was 2, checked in by Yuri Dario, 15 years ago

Initial import for vendor code.

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