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

Last change on this file was 388, checked in by dmik, 11 years ago

python: Update vendor to 2.7.6.

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