我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pdb.py()。
def lookupmodule(self, filename): """Helper function for break/clear parsing -- may be overridden. lookupmodule() translates (possibly incomplete) file or module name into an absolute file name. """ if os.path.isabs(filename) and os.path.exists(filename): return filename f = os.path.join(sys.path[0], filename) if os.path.exists(f) and self.canonic(f) == self.mainpyfile: return f root, ext = os.path.splitext(filename) if ext == '': filename = filename + '.py' if os.path.isabs(filename): return filename for dirname in sys.path: while os.path.islink(dirname): dirname = os.readlink(dirname) fullname = os.path.join(dirname, filename) if os.path.exists(fullname): return fullname return None
def help_hidden_frames(self): print("""\ Some frames might be marked as "hidden": by default, hidden frames are not shown in the stack trace, and cannot be reached using ``up`` and ``down``. You can use ``hf_unhide`` to tell pdb to ignore the hidden status (i.e., to treat hidden frames as normal ones), and ``hf_hide`` to hide them again. ``hf_list`` prints a list of hidden frames. Frames can marked as hidden in the following ways: - by using the @pdb.hideframe function decorator - by having __tracebackhide__=True in the locals or the globals of the function (this hides py.test internal stuff) - by having __unittest=True in the globals of the function (this hides unittest internal stuff) """, file=self.stdout)
def do_edit(self, arg): "Open an editor visiting the current file at the current line" if arg == '': filename, lineno = self._get_current_position() else: filename, lineno, _ = self._get_position_of_arg(arg) if filename is None: return # this case handles code generated with py.code.Source() # filename is something like '<0-codegen foo.py:18>' match = re.match(r'.*<\d+-codegen (.*):(\d+)>', filename) if match: filename = match.group(1) lineno = int(match.group(2)) editor = self.config.editor self._open_editor(editor, lineno, filename)
def test_single_question_mark(): def fn(): def f2(x, y): """Return product of x and y""" return x * y set_trace() a = 1 b = 2 c = 3 return a+b+c # import pdb; pdb.set_trace() check(fn, """ [NUM] > .*fn() -> a = 1 # f2 <function .*f2 at .*> # f2? .*Type:.*function .*String Form:.*<function .*f2 at .*> .*File:.*test_pdb.py .*Definition:.*f2(x, y) .*Docstring:.*Return product of x and y # c """)
def test_py_code_source(): src = py.code.Source(""" def fn(): x = 42 set_trace() return x """) exec(src.compile(), globals()) check(fn, """ [NUM] > .*fn() -> return x # ll NUM def fn(): NUM x = 42 NUM set_trace() NUM -> return x # c """)
def test_continue_arg(): def fn(): set_trace() x = 1 y = 2 z = 3 return x+y+z _, lineno = inspect.getsourcelines(fn) line_z = lineno+4 check(fn, """ [NUM] > .*fn() -> x = 1 # c %d Breakpoint 1 at .*/test_pdb.py:%d Deleted breakpoint 1 [NUM] > .*fn() -> z = 3 # c """ % (line_z, line_z))
def _complete_location(self, text, line, begidx, endidx): # Complete a file/module/function location for break/tbreak/clear. if line.strip().endswith((':', ',')): # Here comes a line number or a condition which we can't complete. return [] # First, try to find matching functions (i.e. expressions). try: ret = self._complete_expression(text, line, begidx, endidx) except Exception: ret = [] # Then, try to complete file names as well. globs = glob.glob(text + '*') for fn in globs: if os.path.isdir(fn): ret.append(fn + '/') elif os.path.isfile(fn) and fn.lower().endswith(('.py', '.pyw')): ret.append(fn + ':') return ret
def help_b(self): print >>self.stdout, """b(reak) ([file:]lineno | function) [, condition] With a line number argument, set a break there in the current file. With a function name, set a break at first executable line of that function. Without argument, list all breaks. If a second argument is present, it is a string specifying an expression which must evaluate to true before the breakpoint is honored. The line number may be prefixed with a filename and a colon, to specify a breakpoint in another file (probably one that hasn't been loaded yet). The file is searched for on sys.path; the .py suffix may be omitted."""
def import_from_stdlib(name): import code # arbitrary module which stays in the same dir as pdb result = types.ModuleType(name) imported = False if hasattr(code, '__loader__'): try: code = code.__loader__.get_code('pdb') except ImportError: pass else: resultd = {} exec(code, resultd) for k, v in resultd.items(): setattr(result, k, v) imported = True if not imported: stdlibdir, _ = os.path.split(code.__file__) pyfile = os.path.join(stdlibdir, name + '.py') with open(pyfile) as f: src = f.read() co_module = compile(src, pyfile, 'exec', dont_inherit=True) exec(co_module, result.__dict__) return result
def _disable_pytest_capture_maybe(self): try: import py.test py.test.config # force to raise ImportError if pytest is not # installed except (ImportError, AttributeError): return try: capman = py.test.config.pluginmanager.getplugin('capturemanager') capman.suspendcapture() except KeyError: pass except AttributeError: pass # newer py.test with support ready, or very old py.test for # which this hack does not work
def test_help(command, expected_regex): from pdb import StringIO instance = PdbTest() instance.stdout = StringIO() # Redirect sys.stdout because Python 2 pdb.py has `print >>self.stdout` for # some functions and plain ol' `print` for others. try: sys.stdout = instance.stdout instance.do_help(command) finally: sys.stdout == sys.__stdout__ output = instance.stdout.getvalue() assert re.search(expected_regex, output)
def test_exception_lineno(): def bar(): assert False def fn(): try: a = 1 bar() b = 2 except AssertionError: xpm() check(fn, """ Traceback (most recent call last): .*File.*test_pdb.py.*, line NUM, in fn bar() .*File.*test_pdb.py.*, line NUM, in bar assert False AssertionError: assert False [NUM] > .*bar() -> assert False # u [NUM] > .*fn() -> bar() # ll NUM def fn(): NUM try: NUM a = 1 NUM >> bar() NUM b = 2 NUM except AssertionError: NUM -> xpm() # c """)
def test_postmortem_needs_exceptioncontext(): try: # py.test bug - doesnt clear the index error from finding the next item sys.exc_clear() except AttributeError: # Python 3 doesn't have sys.exc_clear pass py.test.raises(AssertionError, pdb.post_mortem, Pdb=PdbTest)
def test_exception_through_generator(): def gen(): yield 5 assert False def fn(): try: for i in gen(): pass except AssertionError: xpm() check(fn, """ Traceback (most recent call last): .*test_pdb.py.*, line NUM, in fn .*for i in gen(): .*test_pdb.py.*, line NUM, in gen .*assert False AssertionError: assert False [NUM] > .*gen() -> assert False # u [NUM] > .*fn() -> for i in gen(): # c """)
def test_utf8(): py.test.skip('fails on python 2.7') def fn(): # ???? a = 1 set_trace(Config = ConfigWithHighlight) return a # we cannot easily use "check" because the output is full of ANSI escape # sequences expected, lines = run_func(fn, '# ll\n# c') assert '????' in lines[4]
def do_clear(self, arg): """Three possibilities, tried in this order: clear -> clear all breaks, ask for confirmation clear file:lineno -> clear all breaks at file:lineno clear bpno bpno ... -> clear breakpoints by number""" if not arg: try: reply = raw_input('Clear all breaks? ') except EOFError: reply = 'no' reply = reply.strip().lower() if reply in ('y', 'yes'): self.clear_all_breaks() return if ':' in arg: # Make sure it works for "clear C:\foo\bar.py:12" i = arg.rfind(':') filename = arg[:i] arg = arg[i+1:] try: lineno = int(arg) except ValueError: err = "Invalid line number (%s)" % arg else: err = self.clear_break(filename, lineno) if err: print >>self.stdout, '***', err return numberlist = arg.split() for i in numberlist: try: i = int(i) except ValueError: print >>self.stdout, 'Breakpoint index %r is not a number' % i continue if not (0 <= i < len(bdb.Breakpoint.bpbynumber)): print >>self.stdout, 'No breakpoint numbered', i continue err = self.clear_bpbynumber(i) if err: print >>self.stdout, '***', err else: print >>self.stdout, 'Deleted breakpoint', i
def main(): if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"): print "usage: pdb.py scriptfile [arg] ..." sys.exit(2) mainpyfile = sys.argv[1] # Get script filename if not os.path.exists(mainpyfile): print 'Error:', mainpyfile, 'does not exist' sys.exit(1) del sys.argv[0] # Hide "pdb.py" from argument list # Replace pdb's dir with script's dir in front of module search path. sys.path[0] = os.path.dirname(mainpyfile) # Note on saving/restoring sys.argv: it's a good idea when sys.argv was # modified by the script being debugged. It's a bad idea when it was # changed by the user from the command line. There is a "restart" command # which allows explicit specification of command line arguments. pdb = Pdb() while True: try: pdb._runscript(mainpyfile) if pdb._user_requested_quit: break print "The program finished and will be restarted" except Restart: print "Restarting", mainpyfile, "with arguments:" print "\t" + " ".join(sys.argv[1:]) except SystemExit: # In most cases SystemExit does not warrant a post-mortem session. print "The program exited via sys.exit(). Exit status: ", print sys.exc_info()[1] except: traceback.print_exc() print "Uncaught exception. Entering post mortem debugging" print "Running 'cont' or 'step' will restart the program" t = sys.exc_info()[2] pdb.interaction(None, t) print "Post mortem debugger finished. The " + mainpyfile + \ " will be restarted" # When invoked as main program, invoke the debugger on a script
def main(): if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"): print "usage: pdb.py scriptfile [arg] ..." sys.exit(2) mainpyfile = sys.argv[1] # Get script filename if not os.path.exists(mainpyfile): print 'Error:', mainpyfile, 'does not exist' sys.exit(1) del sys.argv[0] # Hide "pdb.py" from argument list # Replace pdb's dir with script's dir in front of module search path. sys.path[0] = os.path.dirname(mainpyfile) # Note on saving/restoring sys.argv: it's a good idea when sys.argv was # modified by the script being debugged. It's a bad idea when it was # changed by the user from the command line. There is a "restart" command # which allows explicit specification of command line arguments. pdb = Pdb() while True: try: pdb._runscript(mainpyfile) if pdb._user_requested_quit: break print "The program finished and will be restarted" except Restart: print "Restarting", mainpyfile, "with arguments:" print "\t" + " ".join(sys.argv[1:]) except SystemExit: # In most cases SystemExit does not warrant a post-mortem session. print "The program exited via sys.exit(). Exit status: ", print sys.exc_info()[1] except SyntaxError: traceback.print_exc() sys.exit(1) except: traceback.print_exc() print "Uncaught exception. Entering post mortem debugging" print "Running 'cont' or 'step' will restart the program" t = sys.exc_info()[2] pdb.interaction(None, t) print "Post mortem debugger finished. The " + mainpyfile + \ " will be restarted" # When invoked as main program, invoke the debugger on a script