Python pdb.Pdb() Examples
The following are 30
code examples of pdb.Pdb().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pdb
, or try the search function
.
Example #1
Source File: Main.py From arnold-usd with Apache License 2.0 | 6 votes |
def _exec_main(parser, values): sconsflags = os.environ.get('SCONSFLAGS', '') all_args = sconsflags.split() + sys.argv[1:] options, args = parser.parse_args(all_args, values) if isinstance(options.debug, list) and "pdb" in options.debug: import pdb pdb.Pdb().runcall(_main, parser) elif options.profile_file: # compat layer imports "cProfile" for us if it's available. from profile import Profile prof = Profile() try: prof.runcall(_main, parser) finally: prof.dump_stats(options.profile_file) else: _main(parser)
Example #2
Source File: cmd2plus.py From OpenTrader with GNU Lesser General Public License v3.0 | 6 votes |
def set_trace(): """Call pdb.set_trace in the caller's frame. First restore sys.stdout and sys.stderr. Note that the streams are NOT reset to whatever they were before the call once pdb is done! """ import pdb for stream in 'stdout', 'stderr': output = getattr(sys, stream) orig_output = getattr(sys, '__%s__' % stream) if output != orig_output: # Flush the output before entering pdb if hasattr(output, 'getvalue'): orig_output.write(output.getvalue()) orig_output.flush() setattr(sys, stream, orig_output) exc, tb = sys.exc_info()[1:] if tb: if isinstance(exc, AssertionError) and exc.args: # The traceback is not printed yet print_exc() pdb.post_mortem(tb) else: pdb.Pdb().set_trace(sys._getframe().f_back)
Example #3
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_prompt_setter(): p = pdbpp.Pdb() assert p.prompt == "(Pdb++) " p.prompt = "(Pdb)" assert p.prompt == "(Pdb++)" p.prompt = "ipdb> " assert p.prompt == "ipdb++> " p.prompt = "custom" assert p.prompt == "custom++" p.prompt = "custom " assert p.prompt == "custom++ " p.prompt = "custom :" assert p.prompt == "custom++ :" p.prompt = "custom " assert p.prompt == "custom++ " p.prompt = "" assert p.prompt == "" # Not changed (also used in tests). p.prompt = "# " assert p.prompt == "# " # Can be forced. p._prompt = "custom" assert p.prompt == "custom"
Example #4
Source File: pdbpp.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 be 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 is used by pytest) - by having ``__unittest=True`` in the globals of the function (this hides unittest internal stuff) - by providing a list of skip patterns to the Pdb class constructor. This list defaults to ``skip=["importlib._bootstrap"]``. Note that the initial frame where ``set_trace`` was called from is not hidden, except for when using the function decorator. """, file=self.stdout)
Example #5
Source File: pdbpp.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 6 votes |
def do_list(self, arg): """Enhance original do_list with highlighting.""" if not (self.config.use_pygments is not False or self.config.highlight): return super(Pdb, self).do_list(arg) with self._patch_linecache_for_source_highlight(): oldstdout = self.stdout self.stdout = StringIO() ret = super(Pdb, self).do_list(arg) orig_pdb_lines = self.stdout.getvalue().splitlines() self.stdout = oldstdout for line in self._format_color_prefixes(orig_pdb_lines): print(line, file=self.stdout) return ret
Example #6
Source File: pdbpp.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 6 votes |
def set_trace(self, frame=None): """Remember starting frame. This is used with pytest, which does not use pdb.set_trace(). """ if getattr(local, "_pdbpp_completing", False): # Handle set_trace being called during completion, e.g. with # fancycompleter's attr_matches. return if self.disabled: return if frame is None: frame = sys._getframe().f_back self._via_set_trace_frame = frame self._stopped_for_set_trace = False self.start_filename = frame.f_code.co_filename self.start_lineno = frame.f_lineno return super(Pdb, self).set_trace(frame)
Example #7
Source File: pdbpp.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _remove_bdb_context(evalue): """Remove exception context from Pdb from the exception. E.g. "AttributeError: 'Pdb' object has no attribute 'do_foo'", when trying to look up commands (bpo-36494). Only done for Python 3+. """ if not hasattr(evalue, "__context__"): return removed_bdb_context = evalue while removed_bdb_context.__context__: ctx = removed_bdb_context.__context__ if ( isinstance(ctx, AttributeError) and ctx.__traceback__.tb_frame.f_code.co_name == "onecmd" ): removed_bdb_context.__context__ = None break removed_bdb_context = removed_bdb_context.__context__ # simplified interface
Example #8
Source File: pdbpp.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 6 votes |
def break_on_setattr(attrname, condition=always, Pdb=Pdb): def decorator(cls): old___setattr__ = cls.__setattr__ @hideframe def __setattr__(self, attr, value): if attr == attrname and condition(self, value): frame = sys._getframe().f_back pdb_ = Pdb() pdb_.set_trace(frame) pdb_.stopframe = frame pdb_.interaction(frame, None) old___setattr__(self, attr, value) cls.__setattr__ = __setattr__ return cls return decorator
Example #9
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 6 votes |
def set_trace_via_module(frame=None, cleanup=True, Pdb=PdbTest, **kwds): """set_trace helper that goes through pdb.set_trace. It injects Pdb into the globals of pdb.set_trace, to use the given frame. """ if frame is None: frame = sys._getframe().f_back if cleanup: pdbpp.cleanup() class PdbForFrame(Pdb): def set_trace(self, _frame, *args, **kwargs): super(PdbForFrame, self).set_trace(frame, *args, **kwargs) newglobals = pdbpp.set_trace.__globals__.copy() newglobals['Pdb'] = PdbForFrame new_set_trace = pdbpp.rebind_globals(pdbpp.set_trace, newglobals) new_set_trace(**kwds)
Example #10
Source File: tools.py From OpenTrader with GNU Lesser General Public License v3.0 | 6 votes |
def set_trace(): """Call pdb.set_trace in the caller's frame. First restore sys.stdout and sys.stderr. Note that the streams are NOT reset to whatever they were before the call once pdb is done! """ import pdb for stream in 'stdout', 'stderr': output = getattr(sys, stream) orig_output = getattr(sys, '__%s__' % stream) if output != orig_output: # Flush the output before entering pdb if hasattr(output, 'getvalue'): orig_output.write(output.getvalue()) orig_output.flush() setattr(sys, stream, orig_output) exc, tb = sys.exc_info()[1:] if tb: if isinstance(exc, AssertionError) and exc.args: # The traceback is not printed yet print_exc() pdb.post_mortem(tb) else: pdb.Pdb().set_trace(sys._getframe().f_back)
Example #11
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_config_pygments_deprecated_use_terminal256formatter(monkeypatch): import pygments.formatters monkeypatch.setenv("TERM", "xterm-256color") class Config(DefaultConfig): use_terminal256formatter = False assert isinstance( Pdb(Config=Config)._get_pygments_formatter(), pygments.formatters.TerminalFormatter ) class Config(DefaultConfig): use_terminal256formatter = True assert isinstance( Pdb(Config=Config)._get_pygments_formatter(), pygments.formatters.Terminal256Formatter )
Example #12
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_break_on_setattr(): # we don't use a class decorator to keep 2.5 compatibility class Foo(object): pass Foo = pdbpp.break_on_setattr('x', Pdb=PdbTest)(Foo) def fn(): obj = Foo() obj.x = 0 return obj.x check(fn, """ [NUM] > .*fn() -> obj.x = 0 5 frames hidden .* # hasattr(obj, 'x') False # n [NUM] > .*fn() -> return obj.x 5 frames hidden .* # p obj.x 0 # c """)
Example #13
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_handles_set_trace_in_config(tmpdir): """Should not cause a RecursionError.""" def fn(): class Config(ConfigTest): def __init__(self, *args, **kwargs): print("Config.__init__") # Becomes a no-op. set_trace(Config=Config) print("after_set_trace") set_trace(Config=Config) check(fn, r""" Config.__init__ pdb\+\+: using pdb.Pdb for recursive set_trace. > .*__init__() -> print("after_set_trace") (Pdb) c after_set_trace --Return-- [NUM] > .*fn()->None -> set_trace(Config=Config) 5 frames hidden .* # c """)
Example #14
Source File: debugging.py From python-netsurv with MIT License | 5 votes |
def set_trace(cls, *args, **kwargs): """Invoke debugging via ``Pdb.set_trace``, dropping any IO capturing.""" frame = sys._getframe().f_back _pdb = cls._init_pdb("set_trace", *args, **kwargs) _pdb.set_trace(frame)
Example #15
Source File: debugging.py From python-netsurv with MIT License | 5 votes |
def _import_pdb_cls(cls, capman): if not cls._config: # Happens when using pytest.set_trace outside of a test. return pdb.Pdb usepdb_cls = cls._config.getvalue("usepdb_cls") if cls._wrapped_pdb_cls and cls._wrapped_pdb_cls[0] == usepdb_cls: return cls._wrapped_pdb_cls[1] if usepdb_cls: modname, classname = usepdb_cls try: __import__(modname) mod = sys.modules[modname] # Handle --pdbcls=pdb:pdb.Pdb (useful e.g. with pdbpp). parts = classname.split(".") pdb_cls = getattr(mod, parts[0]) for part in parts[1:]: pdb_cls = getattr(pdb_cls, part) except Exception as exc: value = ":".join((modname, classname)) raise UsageError( "--pdbcls: could not import {!r}: {}".format(value, exc) ) else: pdb_cls = pdb.Pdb wrapped_cls = cls._get_pdb_wrapper_class(pdb_cls, capman) cls._wrapped_pdb_cls = (usepdb_cls, wrapped_cls) return wrapped_cls
Example #16
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_break_on_setattr_overridden(): # we don't use a class decorator to keep 2.5 compatibility class Foo(object): def __setattr__(self, attr, value): object.__setattr__(self, attr, value+1) Foo = pdbpp.break_on_setattr('x', Pdb=PdbTest)(Foo) def fn(): obj = Foo() obj.y = 41 obj.x = 0 return obj.x check(fn, """ [NUM] > .*fn() -> obj.x = 0 5 frames hidden .* # obj.y 42 # hasattr(obj, 'x') False # n [NUM] > .*fn() -> return obj.x 5 frames hidden .* # p obj.x 1 # c """)
Example #17
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_break_on_setattr_condition(): def mycond(obj, value): return value == 42 class Foo(object): pass # we don't use a class decorator to keep 2.5 compatibility Foo = pdbpp.break_on_setattr('x', condition=mycond, Pdb=PdbTest)(Foo) def fn(): obj = Foo() obj.x = 0 obj.x = 42 return obj.x check(fn, """ [NUM] > .*fn() -> obj.x = 42 5 frames hidden .* # obj.x 0 # n [NUM] > .*fn() -> return obj.x 5 frames hidden .* # obj.x 42 # c """)
Example #18
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_break_on_setattr_without_hidden_frames(): class PdbWithConfig(PdbTest): def __init__(self, *args, **kwargs): class Config(ConfigTest): enable_hidden_frames = False super(PdbWithConfig, self).__init__(*args, Config=Config, **kwargs) class Foo(object): pass Foo = pdbpp.break_on_setattr('x', Pdb=PdbWithConfig)(Foo) def fn(): obj = Foo() obj.x = 0 return obj.x check(fn, """ [NUM] > .*fn() -> obj.x = 0 # hasattr(obj, 'x') False # n [NUM] > .*fn() -> return obj.x # p obj.x 0 # c """)
Example #19
Source File: doctest_driver.py From razzy-spinner with GNU General Public License v3.0 | 5 votes |
def trace_dispatch(self, *args): save_stdout = sys.stdout sys.stdout = self.__out pdb.Pdb.trace_dispatch(self, *args) sys.stdout = save_stdout
Example #20
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_postmortem_noargs(): def fn(): try: a = 1 # noqa: F841 1/0 except ZeroDivisionError: pdbpp.post_mortem(Pdb=PdbTest) check(fn, """ [NUM] > .*fn() -> 1/0 # c """)
Example #21
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_sticky_dunder_exception_with_highlight(): """Test __exception__ being displayed in sticky mode.""" def fn(): def raises(): raise InnerTestException() set_trace(Config=ConfigWithHighlight) raises() check(fn, """ [NUM] > .*fn() -> raises() 5 frames hidden (try 'help hidden_frames') # n .*InnerTestException.* ### via pdbpp.Pdb.user_exception (differs on py3/py27) [NUM] > .*fn() -> raises() 5 frames hidden .* # sticky <CLEARSCREEN> [NUM] > <COLORFNAME>{filename}<COLORRESET>(<COLORNUM>)fn(), 5 frames hidden <COLORNUM> def fn(): <COLORNUM> def raises(): <COLORNUM> raise InnerTestException() <COLORNUM> <COLORNUM> set_trace(.*) <COLORCURLINE> -> raises().* <COLORLNUM>InnerTestException: <COLORRESET> # c """.format( filename=RE_THIS_FILE_CANONICAL, ))
Example #22
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_longlist_with_changed_source(self): from myfile import fn check(fn, r""" [NUM] > .*fn() -> after_settrace() 5 frames hidden (try 'help hidden_frames') (Pdb++) ll NUM def fn(): NUM set_trace() NUM -> after_settrace() NUM set_trace() NUM a = 3 (Pdb++) rewrite_file() (Pdb++) c [NUM] > .*fn() -> a = 3 5 frames hidden (try 'help hidden_frames') (Pdb++) ll NUM def fn(): NUM set_trace() NUM after_settrace() NUM set_trace() NUM -> a = 3 (Pdb++) c """)
Example #23
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_list_with_changed_source(self): from myfile import fn check(fn, r""" [NUM] > .*fn() -> after_settrace() 5 frames hidden (try 'help hidden_frames') (Pdb++) l NUM \t import linecache$ NUM \t linecache.checkcache()$ NUM \t$ NUM \tdef fn(): NUM \t set_trace() NUM ->\t after_settrace() NUM \t set_trace() NUM \t a = 3 [EOF] (Pdb++) rewrite_file() (Pdb++) c [NUM] > .*fn() -> a = 3 5 frames hidden (try 'help hidden_frames') (Pdb++) l NUM \t NUM \tdef fn(): NUM \t set_trace() NUM \t after_settrace() NUM \t set_trace() NUM ->\t a = 3 [EOF] (Pdb++) c """)
Example #24
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_shortlist_with_pygments(config, monkeypatch): def fn(): a = 1 set_trace(Config=config) return a calls = [] orig_get_func = pdbpp.Pdb._get_source_highlight_function def check_calls(self): orig_highlight = orig_get_func(self) calls.append(["get", self]) def new_highlight(src): calls.append(["highlight", src]) return orig_highlight(src) return new_highlight monkeypatch.setattr(pdbpp.Pdb, "_get_source_highlight_function", check_calls) check(fn, """ [NUM] > .*fn() -> ^[[38;5;28;01mreturn^[[39;00m a 5 frames hidden .* # l {line_num}, 5 NUM +\t$ NUM +\t ^[[38;5;28;01mdef^[[39;00m ^[[38;5;21mfn^[[39m(): NUM +\t a ^[[38;5;241m=^[[39m ^[[38;5;241m1^[[39m NUM +\t set_trace(Config^[[38;5;241m=^[[39mconfig) NUM +\t$ NUM +->\t ^[[38;5;28;01mreturn^[[39;00m a # c """.format(line_num=fn.__code__.co_firstlineno - 1)) assert len(calls) == 3, calls
Example #25
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_top_bottom_frame_post_mortem(): def fn(): def throws(): 0 / 0 def f(): throws() try: f() except: pdbpp.post_mortem(Pdb=PdbTest) check(fn, r""" [2] > .*throws() -> 0 / 0 # top [0] > .*fn() -> f() # top \*\*\* Oldest frame # bottom [2] > .*throws() -> 0 / 0 # bottom \*\*\* Newest frame # frame -1 ### Same as bottom, no error. [2] > .*throws() -> 0 / 0 # frame -2 [1] > .*f() -> throws() # frame -3 \*\*\* Out of range # c """)
Example #26
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_global_pdb_only_reused_for_same_class(monkeypatch_pdb_methods): def fn(): class NewPdb(PdbTest, pdbpp.Pdb): def set_trace(self, *args): print("new_set_trace") ret = super(NewPdb, self).set_trace(*args) return ret new_pdb = NewPdb() new_pdb.set_trace() assert pdbpp.local.GLOBAL_PDB is new_pdb set_trace(cleanup=False) assert pdbpp.local.GLOBAL_PDB is not new_pdb # What "debug" does, for coverage. new_pdb = NewPdb() new_pdb.set_trace() assert pdbpp.local.GLOBAL_PDB is new_pdb pdbpp.local.GLOBAL_PDB._use_global_pdb_for_class = PdbTest set_trace(cleanup=False) assert pdbpp.local.GLOBAL_PDB is new_pdb # Explicit kwarg for coverage. new_pdb = NewPdb(set_global_pdb=False) new_pdb.set_trace() assert pdbpp.local.GLOBAL_PDB is not new_pdb check(fn, """ new_set_trace === set_trace === set_trace new_set_trace === set_trace new_set_trace === set_trace new_set_trace === set_trace """)
Example #27
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_global_pdb_can_be_skipped_but_set(): def fn(): set_trace() first = pdbpp.local.GLOBAL_PDB assert isinstance(first, PdbTest) class NewPdb(PdbTest, pdbpp.Pdb): def set_trace(self, *args): print("new_set_trace") assert pdbpp.local.GLOBAL_PDB is self ret = super(NewPdb, self).set_trace(*args) assert pdbpp.local.GLOBAL_PDB is self return ret new_pdb = NewPdb(use_global_pdb=False, set_global_pdb=True) new_pdb.set_trace() assert pdbpp.local.GLOBAL_PDB is new_pdb set_trace(cleanup=False) assert pdbpp.local.GLOBAL_PDB is new_pdb check(fn, """ [NUM] > .*fn() -> first = pdbpp.local.GLOBAL_PDB 5 frames hidden .* # c new_set_trace [NUM] .*set_trace() -> assert pdbpp.local.GLOBAL_PDB is self 5 frames hidden .* # readline_ = pdbpp.local.GLOBAL_PDB.fancycompleter.config.readline # assert readline_.get_completer() == pdbpp.local.GLOBAL_PDB.complete # c new_set_trace [NUM] > .*fn() -> assert pdbpp.local.GLOBAL_PDB is new_pdb 5 frames hidden .* # c """)
Example #28
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_global_pdb_can_be_skipped_unit(monkeypatch_pdb_methods): """Same as test_global_pdb_can_be_skipped, but with mocked Pdb methods.""" def fn(): set_trace() first = pdbpp.local.GLOBAL_PDB assert isinstance(first, PdbTest) class NewPdb(PdbTest, pdbpp.Pdb): def set_trace(self, *args): print("new_set_trace") assert pdbpp.local.GLOBAL_PDB is not self ret = super(NewPdb, self).set_trace(*args) assert pdbpp.local.GLOBAL_PDB is not self return ret new_pdb = NewPdb(use_global_pdb=False) new_pdb.set_trace() assert pdbpp.local.GLOBAL_PDB is not new_pdb set_trace(cleanup=False) assert pdbpp.local.GLOBAL_PDB is not new_pdb check(fn, """ === set_trace new_set_trace === set_trace === set_trace """)
Example #29
Source File: doctest24.py From mishkal with GNU General Public License v3.0 | 5 votes |
def trace_dispatch(self, *args): # Redirect stdout to the given stream. save_stdout = sys.stdout sys.stdout = self.__out # Call Pdb's trace dispatch method. try: return pdb.Pdb.trace_dispatch(self, *args) finally: sys.stdout = save_stdout # [XX] Normalize with respect to os.path.pardir?
Example #30
Source File: test_pdb.py From pdbpp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_global_pdb_can_be_skipped(): def fn(): set_trace() first = pdbpp.local.GLOBAL_PDB assert isinstance(first, PdbTest) class NewPdb(PdbTest, pdbpp.Pdb): def set_trace(self, *args): print("new_set_trace") assert pdbpp.local.GLOBAL_PDB is not self ret = super(NewPdb, self).set_trace(*args) assert pdbpp.local.GLOBAL_PDB is not self return ret new_pdb = NewPdb(use_global_pdb=False) new_pdb.set_trace() assert pdbpp.local.GLOBAL_PDB is not new_pdb set_trace(cleanup=False) assert pdbpp.local.GLOBAL_PDB is not new_pdb check(fn, """ [NUM] > .*fn() -> first = pdbpp.local.GLOBAL_PDB 5 frames hidden .* # c new_set_trace [NUM] .*set_trace() -> assert pdbpp.local.GLOBAL_PDB is not self 5 frames hidden .* # readline_ = pdbpp.local.GLOBAL_PDB.fancycompleter.config.readline # assert readline_.get_completer() != pdbpp.local.GLOBAL_PDB.complete # c [NUM] > .*fn() -> assert pdbpp.local.GLOBAL_PDB is not new_pdb 5 frames hidden .* # c """)