3 """A Python debugger."""
5 # (See pdb.doc for documentation.)
16 # Create a custom safe Repr instance and increase its maxstring.
17 # The default of 30 truncates error messages too easily.
20 _saferepr
= _repr
.repr
22 __all__
= ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
23 "post_mortem", "help"]
25 def find_function(funcname
, filename
):
26 cre
= re
.compile(r
'def\s+%s\s*[(]' % funcname
)
31 # consumer of this info expects the first line to be 1
39 answer
= funcname
, filename
, lineno
46 # Interaction prompt line will separate file and call info from code
47 # text using value of line_prefix string. A newline and arrow may
48 # be to your liking. You can set it once pdb is imported using the
49 # command "pdb.line_prefix = '\n% '".
50 # line_prefix = ': ' # Use this to get the old situation back
51 line_prefix
= '\n-> ' # Probably a better default
53 class Pdb(bdb
.Bdb
, cmd
.Cmd
):
56 bdb
.Bdb
.__init
__(self
)
57 cmd
.Cmd
.__init
__(self
)
58 self
.prompt
= '(Pdb) '
61 self
._wait
_for
_mainpyfile
= 0
62 # Try to load readline if it exists
68 # Read $HOME/.pdbrc and ./.pdbrc
70 if 'HOME' in os
.environ
:
71 envHome
= os
.environ
['HOME']
73 rcFile
= open(os
.path
.join(envHome
, ".pdbrc"))
77 for line
in rcFile
.readlines():
78 self
.rcLines
.append(line
)
81 rcFile
= open(".pdbrc")
85 for line
in rcFile
.readlines():
86 self
.rcLines
.append(line
)
99 def setup(self
, f
, t
):
101 self
.stack
, self
.curindex
= self
.get_stack(f
, t
)
102 self
.curframe
= self
.stack
[self
.curindex
][0]
105 # Can be executed earlier than 'setup' if desired
106 def execRcLines(self
):
108 # Make local copy because of recursion
109 rcLines
= self
.rcLines
114 if len(line
) > 0 and line
[0] != '#':
117 # Override Bdb methods
119 def user_call(self
, frame
, argument_list
):
120 """This method is called when there is the remote possibility
121 that we ever need to stop in this function."""
122 if self
._wait
_for
_mainpyfile
:
124 if self
.stop_here(frame
):
126 self
.interaction(frame
, None)
128 def user_line(self
, frame
):
129 """This function is called when we stop or break at this line."""
130 if self
._wait
_for
_mainpyfile
:
131 if (self
.mainpyfile
!= self
.canonic(frame
.f_code
.co_filename
)
132 or frame
.f_lineno
<= 0):
134 self
._wait
_for
_mainpyfile
= 0
135 self
.interaction(frame
, None)
137 def user_return(self
, frame
, return_value
):
138 """This function is called when a return trap is set here."""
139 frame
.f_locals
['__return__'] = return_value
141 self
.interaction(frame
, None)
143 def user_exception(self
, frame
, (exc_type
, exc_value
, exc_traceback
)):
144 """This function is called if an exception occurs,
145 but only if we are to stop at or just below this level."""
146 frame
.f_locals
['__exception__'] = exc_type
, exc_value
147 if type(exc_type
) == type(''):
148 exc_type_name
= exc_type
149 else: exc_type_name
= exc_type
.__name
__
150 print exc_type_name
+ ':', _saferepr(exc_value
)
151 self
.interaction(frame
, exc_traceback
)
153 # General interaction function
155 def interaction(self
, frame
, traceback
):
156 self
.setup(frame
, traceback
)
157 self
.print_stack_entry(self
.stack
[self
.curindex
])
161 def default(self
, line
):
162 if line
[:1] == '!': line
= line
[1:]
163 locals = self
.curframe
.f_locals
164 globals = self
.curframe
.f_globals
166 code
= compile(line
+ '\n', '<stdin>', 'single')
167 exec code
in globals, locals
169 t
, v
= sys
.exc_info()[:2]
170 if type(t
) == type(''):
172 else: exc_type_name
= t
.__name
__
173 print '***', exc_type_name
+ ':', v
175 def precmd(self
, line
):
176 """Handle alias expansion and ';;' separator."""
180 while args
[0] in self
.aliases
:
181 line
= self
.aliases
[args
[0]]
183 for tmpArg
in args
[1:]:
184 line
= line
.replace("%" + str(ii
),
187 line
= line
.replace("%*", ' '.join(args
[1:]))
189 # split into ';;' separated commands
190 # unless it's an alias command
191 if args
[0] != 'alias':
192 marker
= line
.find(';;')
194 # queue up everything after marker
195 next
= line
[marker
+2:].lstrip()
196 self
.cmdqueue
.append(next
)
197 line
= line
[:marker
].rstrip()
200 # Command definitions, called by cmdloop()
201 # The argument is the remaining string on the command line
202 # Return true to exit from the command loop
204 do_h
= cmd
.Cmd
.do_help
206 def do_break(self
, arg
, temporary
= 0):
207 # break [ ([filename:]lineno | function) [, "condition"] ]
209 if self
.breaks
: # There's at least one
210 print "Num Type Disp Enb Where"
211 for bp
in bdb
.Breakpoint
.bpbynumber
:
215 # parse arguments; comma has lowest precedence
216 # and cannot occur in filename
220 comma
= arg
.find(',')
222 # parse stuff after comma: "condition"
223 cond
= arg
[comma
+1:].lstrip()
224 arg
= arg
[:comma
].rstrip()
225 # parse stuff before comma: [filename:]lineno | function
226 colon
= arg
.rfind(':')
229 filename
= arg
[:colon
].rstrip()
230 f
= self
.lookupmodule(filename
)
232 print '*** ', repr(filename
),
233 print 'not found from sys.path'
237 arg
= arg
[colon
+1:].lstrip()
240 except ValueError, msg
:
241 print '*** Bad lineno:', arg
244 # no colon; can be lineno or function
250 self
.curframe
.f_globals
,
251 self
.curframe
.f_locals
)
255 if hasattr(func
, 'im_func'):
257 code
= func
.func_code
258 #use co_name to identify the bkpt (function names
259 #could be aliased, but co_name is invariant)
260 funcname
= code
.co_name
261 lineno
= code
.co_firstlineno
262 filename
= code
.co_filename
265 (ok
, filename
, ln
) = self
.lineinfo(arg
)
267 print '*** The specified object',
269 print 'is not a function'
270 print ('or was not found '
273 funcname
= ok
# ok contains a function name
276 filename
= self
.defaultFile()
277 # Check for reasonable breakpoint
278 line
= self
.checkline(filename
, lineno
)
280 # now set the break point
281 err
= self
.set_break(filename
, line
, temporary
, cond
, funcname
)
282 if err
: print '***', err
284 bp
= self
.get_breaks(filename
, line
)[-1]
285 print "Breakpoint %d at %s:%d" % (bp
.number
,
289 # To be overridden in derived debuggers
290 def defaultFile(self
):
291 """Produce a reasonable default."""
292 filename
= self
.curframe
.f_code
.co_filename
293 if filename
== '<string>' and self
.mainpyfile
:
294 filename
= self
.mainpyfile
299 def do_tbreak(self
, arg
):
300 self
.do_break(arg
, 1)
302 def lineinfo(self
, identifier
):
303 failed
= (None, None, None)
304 # Input is identifier, may be in single quotes
305 idstring
= identifier
.split("'")
306 if len(idstring
) == 1:
307 # not in single quotes
308 id = idstring
[0].strip()
309 elif len(idstring
) == 3:
311 id = idstring
[1].strip()
314 if id == '': return failed
315 parts
= id.split('.')
316 # Protection for derived debuggers
317 if parts
[0] == 'self':
321 # Best first guess at file to look at
322 fname
= self
.defaultFile()
326 # More than one part.
327 # First is module, second is method/class
328 f
= self
.lookupmodule(parts
[0])
332 answer
= find_function(item
, fname
)
333 return answer
or failed
335 def checkline(self
, filename
, lineno
):
336 """Check whether specified line seems to be executable.
338 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
339 line or EOF). Warning: testing is not comprehensive.
341 line
= linecache
.getline(filename
, lineno
)
346 # Don't allow setting breakpoint at a blank line
347 if (not line
or (line
[0] == '#') or
348 (line
[:3] == '"""') or line
[:3] == "'''"):
349 print '*** Blank or comment'
353 def do_enable(self
, arg
):
359 print 'Breakpoint index %r is not a number' % i
362 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
363 print 'No breakpoint numbered', i
366 bp
= bdb
.Breakpoint
.bpbynumber
[i
]
370 def do_disable(self
, arg
):
376 print 'Breakpoint index %r is not a number' % i
379 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
380 print 'No breakpoint numbered', i
383 bp
= bdb
.Breakpoint
.bpbynumber
[i
]
387 def do_condition(self
, arg
):
388 # arg is breakpoint number and condition
389 args
= arg
.split(' ', 1)
390 bpnum
= int(args
[0].strip())
395 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
399 print 'Breakpoint', bpnum
,
400 print 'is now unconditional.'
402 def do_ignore(self
,arg
):
403 """arg is bp number followed by ignore count."""
405 bpnum
= int(args
[0].strip())
407 count
= int(args
[1].strip())
410 bp
= bdb
.Breakpoint
.bpbynumber
[bpnum
]
414 reply
= 'Will ignore next '
416 reply
= reply
+ '%d crossings' % count
418 reply
= reply
+ '1 crossing'
419 print reply
+ ' of breakpoint %d.' % bpnum
421 print 'Will stop next time breakpoint',
422 print bpnum
, 'is reached.'
424 def do_clear(self
, arg
):
425 """Three possibilities, tried in this order:
426 clear -> clear all breaks, ask for confirmation
427 clear file:lineno -> clear all breaks at file:lineno
428 clear bpno bpno ... -> clear breakpoints by number"""
431 reply
= raw_input('Clear all breaks? ')
434 reply
= reply
.strip().lower()
435 if reply
in ('y', 'yes'):
436 self
.clear_all_breaks()
439 # Make sure it works for "clear C:\foo\bar.py:12"
446 err
= "Invalid line number (%s)" % arg
448 err
= self
.clear_break(filename
, lineno
)
449 if err
: print '***', err
451 numberlist
= arg
.split()
453 if not (0 <= i
< len(bdb
.Breakpoint
.bpbynumber
)):
454 print 'No breakpoint numbered', i
456 err
= self
.clear_bpbynumber(i
)
460 print 'Deleted breakpoint', i
461 do_cl
= do_clear
# 'c' is already an abbreviation for 'continue'
463 def do_where(self
, arg
):
464 self
.print_stack_trace()
468 def do_up(self
, arg
):
469 if self
.curindex
== 0:
470 print '*** Oldest frame'
472 self
.curindex
= self
.curindex
- 1
473 self
.curframe
= self
.stack
[self
.curindex
][0]
474 self
.print_stack_entry(self
.stack
[self
.curindex
])
478 def do_down(self
, arg
):
479 if self
.curindex
+ 1 == len(self
.stack
):
480 print '*** Newest frame'
482 self
.curindex
= self
.curindex
+ 1
483 self
.curframe
= self
.stack
[self
.curindex
][0]
484 self
.print_stack_entry(self
.stack
[self
.curindex
])
488 def do_step(self
, arg
):
493 def do_next(self
, arg
):
494 self
.set_next(self
.curframe
)
498 def do_return(self
, arg
):
499 self
.set_return(self
.curframe
)
503 def do_continue(self
, arg
):
506 do_c
= do_cont
= do_continue
508 def do_jump(self
, arg
):
509 if self
.curindex
+ 1 != len(self
.stack
):
510 print "*** You can only jump within the bottom frame"
515 print "*** The 'jump' command requires a line number."
518 # Do the jump, fix up our copy of the stack, and display the
520 self
.curframe
.f_lineno
= arg
521 self
.stack
[self
.curindex
] = self
.stack
[self
.curindex
][0], arg
522 self
.print_stack_entry(self
.stack
[self
.curindex
])
523 except ValueError, e
:
524 print '*** Jump failed:', e
527 def do_debug(self
, arg
):
529 globals = self
.curframe
.f_globals
530 locals = self
.curframe
.f_locals
532 p
.prompt
= "(%s) " % self
.prompt
.strip()
533 print "ENTERING RECURSIVE DEBUGGER"
534 sys
.call_tracing(p
.run
, (arg
, globals, locals))
535 print "LEAVING RECURSIVE DEBUGGER"
536 sys
.settrace(self
.trace_dispatch
)
537 self
.lastcmd
= p
.lastcmd
539 def do_quit(self
, arg
):
540 self
._user
_requested
_quit
= 1
547 def do_EOF(self
, arg
):
549 self
._user
_requested
_quit
= 1
553 def do_args(self
, arg
):
558 if co
.co_flags
& 4: n
= n
+1
559 if co
.co_flags
& 8: n
= n
+1
561 name
= co
.co_varnames
[i
]
563 if name
in dict: print dict[name
]
564 else: print "*** undefined ***"
567 def do_retval(self
, arg
):
568 if '__return__' in self
.curframe
.f_locals
:
569 print self
.curframe
.f_locals
['__return__']
571 print '*** Not yet returned!'
574 def _getval(self
, arg
):
576 return eval(arg
, self
.curframe
.f_globals
,
577 self
.curframe
.f_locals
)
579 t
, v
= sys
.exc_info()[:2]
580 if isinstance(t
, str):
582 else: exc_type_name
= t
.__name
__
583 print '***', exc_type_name
+ ':', repr(v
)
588 print repr(self
._getval
(arg
))
592 def do_pp(self
, arg
):
594 pprint
.pprint(self
._getval
(arg
))
598 def do_list(self
, arg
):
599 self
.lastcmd
= 'list'
603 x
= eval(arg
, {}, {})
604 if type(x
) == type(()):
609 # Assume it's a count
612 first
= max(1, int(x
) - 5)
614 print '*** Error in argument:', repr(arg
)
616 elif self
.lineno
is None:
617 first
= max(1, self
.curframe
.f_lineno
- 5)
619 first
= self
.lineno
+ 1
622 filename
= self
.curframe
.f_code
.co_filename
623 breaklist
= self
.get_file_breaks(filename
)
625 for lineno
in range(first
, last
+1):
626 line
= linecache
.getline(filename
, lineno
)
631 s
= repr(lineno
).rjust(3)
632 if len(s
) < 4: s
= s
+ ' '
633 if lineno
in breaklist
: s
= s
+ 'B'
635 if lineno
== self
.curframe
.f_lineno
:
637 print s
+ '\t' + line
,
639 except KeyboardInterrupt:
643 def do_whatis(self
, arg
):
645 value
= eval(arg
, self
.curframe
.f_globals
,
646 self
.curframe
.f_locals
)
648 t
, v
= sys
.exc_info()[:2]
649 if type(t
) == type(''):
651 else: exc_type_name
= t
.__name
__
652 print '***', exc_type_name
+ ':', repr(v
)
656 try: code
= value
.func_code
659 print 'Function', code
.co_name
661 # Is it an instance method?
662 try: code
= value
.im_func
.func_code
665 print 'Method', code
.co_name
667 # None of the above...
670 def do_alias(self
, arg
):
673 keys
= self
.aliases
.keys()
676 print "%s = %s" % (alias
, self
.aliases
[alias
])
678 if args
[0] in self
.aliases
and len(args
) == 1:
679 print "%s = %s" % (args
[0], self
.aliases
[args
[0]])
681 self
.aliases
[args
[0]] = ' '.join(args
[1:])
683 def do_unalias(self
, arg
):
685 if len(args
) == 0: return
686 if args
[0] in self
.aliases
:
687 del self
.aliases
[args
[0]]
689 # Print a traceback starting at the top stack frame.
690 # The most recently entered frame is printed last;
691 # this is different from dbx and gdb, but consistent with
692 # the Python interpreter's stack trace.
693 # It is also consistent with the up/down commands (which are
694 # compatible with dbx and gdb: up moves towards 'main()'
695 # and down moves towards the most recent stack frame).
697 def print_stack_trace(self
):
699 for frame_lineno
in self
.stack
:
700 self
.print_stack_entry(frame_lineno
)
701 except KeyboardInterrupt:
704 def print_stack_entry(self
, frame_lineno
, prompt_prefix
=line_prefix
):
705 frame
, lineno
= frame_lineno
706 if frame
is self
.curframe
:
710 print self
.format_stack_entry(frame_lineno
, prompt_prefix
)
713 # Help methods (derived from pdb.doc)
720 Without argument, print the list of available commands.
721 With a command name as argument, print help about that command
722 "help pdb" pipes the full documentation file to the $PAGER
723 "help exec" gives help on the ! command"""
725 def help_where(self
):
730 Print a stack trace, with the most recent frame at the bottom.
731 An arrow indicates the "current frame", which determines the
732 context of most commands. 'bt' is an alias for this command."""
741 Move the current frame one level down in the stack trace
742 (to a newer frame)."""
749 Move the current frame one level up in the stack trace
750 (to an older frame)."""
752 def help_break(self
):
756 print """b(reak) ([file:]lineno | function) [, condition]
757 With a line number argument, set a break there in the current
758 file. With a function name, set a break at first executable line
759 of that function. Without argument, list all breaks. If a second
760 argument is present, it is a string specifying an expression
761 which must evaluate to true before the breakpoint is honored.
763 The line number may be prefixed with a filename and a colon,
764 to specify a breakpoint in another file (probably one that
765 hasn't been loaded yet). The file is searched for on sys.path;
766 the .py suffix may be omitted."""
768 def help_clear(self
):
772 print "cl(ear) filename:lineno"
773 print """cl(ear) [bpnumber [bpnumber...]]
774 With a space separated list of breakpoint numbers, clear
775 those breakpoints. Without argument, clear all breaks (but
776 first ask confirmation). With a filename:lineno argument,
777 clear all breaks at that line in that file.
779 Note that the argument is different from previous versions of
780 the debugger (in python distributions 1.5.1 and before) where
781 a linenumber was used instead of either filename:lineno or
782 breakpoint numbers."""
784 def help_tbreak(self
):
785 print """tbreak same arguments as break, but breakpoint is
786 removed when first hit."""
788 def help_enable(self
):
789 print """enable bpnumber [bpnumber ...]
790 Enables the breakpoints given as a space separated list of
793 def help_disable(self
):
794 print """disable bpnumber [bpnumber ...]
795 Disables the breakpoints given as a space separated list of
798 def help_ignore(self
):
799 print """ignore bpnumber count
800 Sets the ignore count for the given breakpoint number. A breakpoint
801 becomes active when the ignore count is zero. When non-zero, the
802 count is decremented each time the breakpoint is reached and the
803 breakpoint is not disabled and any associated condition evaluates
806 def help_condition(self
):
807 print """condition bpnumber str_condition
808 str_condition is a string specifying an expression which
809 must evaluate to true before the breakpoint is honored.
810 If str_condition is absent, any existing condition is removed;
811 i.e., the breakpoint is made unconditional."""
818 Execute the current line, stop at the first possible occasion
819 (either in a function that is called or in the current function)."""
826 Continue execution until the next line in the current function
827 is reached or it returns."""
829 def help_return(self
):
834 Continue execution until the current function returns."""
836 def help_continue(self
):
843 print """c(ont(inue))
844 Continue execution, only stop when a breakpoint is encountered."""
850 print """j(ump) lineno
851 Set the next line that will be executed."""
853 def help_debug(self
):
855 Enter a recursive debugger that steps through the code argument
856 (which is an arbitrary expression or statement to be executed
857 in the current environment)."""
863 print """l(ist) [first [,last]]
864 List source code for the current file.
865 Without arguments, list 11 lines around the current line
866 or continue the previous listing.
867 With one argument, list 11 lines starting at that line.
868 With two arguments, list the given range;
869 if the second argument is less than the first, it is a count."""
876 Print the arguments of the current function."""
879 print """p expression
880 Print the value of the expression."""
883 print """pp expression
884 Pretty-print the value of the expression."""
887 print """(!) statement
888 Execute the (one-line) statement in the context of
889 the current stack frame.
890 The exclamation point can be omitted unless the first word
891 of the statement resembles a debugger command.
892 To assign to a global variable you must always prefix the
893 command with a 'global' command, e.g.:
894 (Pdb) global list_options; list_options = ['-l']
901 print """q(uit) or exit - Quit from the debugger.
902 The program being executed is aborted."""
906 def help_whatis(self
):
908 Prints the type of the argument."""
912 Handles the receipt of EOF as a command."""
914 def help_alias(self
):
915 print """alias [name [command [parameter parameter ...] ]]
916 Creates an alias called 'name' the executes 'command'. The command
917 must *not* be enclosed in quotes. Replaceable parameters are
918 indicated by %1, %2, and so on, while %* is replaced by all the
919 parameters. If no command is given, the current alias for name
920 is shown. If no name is given, all aliases are listed.
922 Aliases may be nested and can contain anything that can be
923 legally typed at the pdb prompt. Note! You *can* override
924 internal pdb commands with aliases! Those internal commands
925 are then hidden until the alias is removed. Aliasing is recursively
926 applied to the first word of the command line; all other words
927 in the line are left alone.
929 Some useful aliases (especially when placed in the .pdbrc file) are:
931 #Print instance variables (usage "pi classInst")
932 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
934 #Print instance variables in self
938 def help_unalias(self
):
939 print """unalias name
940 Deletes the specified alias."""
945 def lookupmodule(self
, filename
):
946 """Helper function for break/clear parsing -- may be overridden.
948 lookupmodule() translates (possibly incomplete) file or module name
949 into an absolute file name.
951 if os
.path
.isabs(filename
) and os
.path
.exists(filename
):
953 f
= os
.path
.join(sys
.path
[0], filename
)
954 if os
.path
.exists(f
) and self
.canonic(f
) == self
.mainpyfile
:
956 root
, ext
= os
.path
.splitext(filename
)
958 filename
= filename
+ '.py'
959 if os
.path
.isabs(filename
):
961 for dirname
in sys
.path
:
962 while os
.path
.islink(dirname
):
963 dirname
= os
.readlink(dirname
)
964 fullname
= os
.path
.join(dirname
, filename
)
965 if os
.path
.exists(fullname
):
969 def _runscript(self
, filename
):
970 # Start with fresh empty copy of globals and locals and tell the script
971 # that it's being run as __main__ to avoid scripts being able to access
972 # the pdb.py namespace.
973 globals_
= {"__name__" : "__main__"}
976 # When bdb sets tracing, a number of call and line events happens
977 # BEFORE debugger even reaches user's code (and the exact sequence of
978 # events depends on python version). So we take special measures to
979 # avoid stopping before we reach the main script (see user_line and
980 # user_call for details).
981 self
._wait
_for
_mainpyfile
= 1
982 self
.mainpyfile
= self
.canonic(filename
)
983 self
._user
_requested
_quit
= 0
984 statement
= 'execfile( "%s")' % filename
985 self
.run(statement
, globals=globals_
, locals=locals_
)
987 # Simplified interface
989 def run(statement
, globals=None, locals=None):
990 Pdb().run(statement
, globals, locals)
992 def runeval(expression
, globals=None, locals=None):
993 return Pdb().runeval(expression
, globals, locals)
995 def runctx(statement
, globals, locals):
997 run(statement
, globals, locals)
999 def runcall(*args
, **kwds
):
1000 return Pdb().runcall(*args
, **kwds
)
1003 Pdb().set_trace(sys
._getframe
().f_back
)
1005 # Post-Mortem interface
1010 while t
.tb_next
is not None:
1012 p
.interaction(t
.tb_frame
, t
)
1015 post_mortem(sys
.last_traceback
)
1018 # Main program for testing
1020 TESTCMD
= 'import x; x.main()'
1027 for dirname
in sys
.path
:
1028 fullname
= os
.path
.join(dirname
, 'pdb.doc')
1029 if os
.path
.exists(fullname
):
1030 sts
= os
.system('${PAGER-more} '+fullname
)
1031 if sts
: print '*** Pager exit status:', sts
1034 print 'Sorry, can\'t find the help file "pdb.doc"',
1035 print 'along the Python search path'
1038 if not sys
.argv
[1:]:
1039 print "usage: pdb.py scriptfile [arg] ..."
1042 mainpyfile
= sys
.argv
[1] # Get script filename
1043 if not os
.path
.exists(mainpyfile
):
1044 print 'Error:', mainpyfile
, 'does not exist'
1047 del sys
.argv
[0] # Hide "pdb.py" from argument list
1049 # Replace pdb's dir with script's dir in front of module search path.
1050 sys
.path
[0] = os
.path
.dirname(mainpyfile
)
1052 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
1053 # modified by the script being debugged. It's a bad idea when it was
1054 # changed by the user from the command line. The best approach would be to
1055 # have a "restart" command which would allow explicit specification of
1056 # command line arguments.
1060 pdb
._runscript
(mainpyfile
)
1061 if pdb
._user
_requested
_quit
:
1063 print "The program finished and will be restarted"
1065 # In most cases SystemExit does not warrant a post-mortem session.
1066 print "The program exited via sys.exit(). Exit status: ",
1067 print sys
.exc_info()[1]
1069 traceback
.print_exc()
1070 print "Uncaught exception. Entering post mortem debugging"
1071 print "Running 'cont' or 'step' will restart the program"
1072 t
= sys
.exc_info()[2]
1073 while t
.tb_next
is not None:
1075 pdb
.interaction(t
.tb_frame
,t
)
1076 print "Post mortem debugger finished. The "+mainpyfile
+" will be restarted"
1079 # When invoked as main program, invoke the debugger on a script
1080 if __name__
=='__main__':