Python ipdb.post_mortem() Examples

The following are 16 code examples of ipdb.post_mortem(). 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 ipdb , or try the search function .
Example #1
Source File: environment.py    From beavy with Mozilla Public License 2.0 6 votes vote down vote up
def after_step(context, step):
    if BEHAVE_DEBUG_ON_ERROR and step.status == "failed":
        # -- ENTER DEBUGGER: Zoom in on failure location.
        # NOTE: Use IPython debugger, same for pdb (basic python debugger).
        try:
            import ipdb as pdb
        except ImportError:
            import pdb

        if getattr(context, "browser", None):
            pprint(context.browser.driver.get_log('browser')[-10:])
            print("Current Screen: {}".format(context.browser.screenshot()))

        pdb.post_mortem(step.exc_traceback) 
Example #2
Source File: utils.py    From ms_deisotope with Apache License 2.0 6 votes vote down vote up
def register_debug_hook():
    import traceback

    def info(type, value, tb):
        if hasattr(sys, 'ps1') or not sys.stderr.isatty():
            sys.__excepthook__(type, value, tb)
        else:
            try:
                import ipdb as pdb_api
            except ImportError:
                import pdb as pdb_api
            traceback.print_exception(type, value, tb)
            pdb_api.post_mortem(tb)

    sys.excepthook = info
    logging.basicConfig(level="DEBUG") 
Example #3
Source File: __init__.py    From python-libmaas with GNU Affero General Public License v3.0 6 votes vote down vote up
def post_mortem(traceback):
    """Work with an exception in a post-mortem debugger.

    Try to use `ipdb` first, falling back to `pdb`.
    """
    try:
        from ipdb import post_mortem
    except ImportError:
        from pdb import post_mortem

    message = "Entering post-mortem debugger. Type `help` for help."
    redline = colorized("{autored}%s{/autored}") % "{0:=^{1}}"

    print()
    print(redline.format(" CRASH! ", len(message)))
    print(message)
    print(redline.format("", len(message)))
    print()

    post_mortem(traceback) 
Example #4
Source File: environment.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def _debug_on_error(context, step):
    if context.config.userdata.getbool("debug"):
        try:
            import ipdb
            ipdb.post_mortem(step.exc_traceback)
        except ImportError:
            import pdb
            pdb.post_mortem(step.exc_traceback) 
Example #5
Source File: shell.py    From alma-slipsomat with MIT License 5 votes vote down vote up
def handle_exception(self, e):
        print("\nException:", e)
        traceback.print_exc(file=sys.stdout)

        answer = questionary.select(
            'Now what?',
            choices=[
                'Restart browser',
                'Debug with ipdb',
                'Debug with pdb',
                'Exit',
            ]
        ).ask()

        if answer == 'Debug with ipdb':
            try:
                import ipdb
            except ImportError:
                print('Please run "pip install ipdb" to install ipdb')
                sys.exit(1)
            ipdb.post_mortem()
        elif answer == 'Debug with pdb':
            import pdb
            pdb.post_mortem()
        elif answer == 'Restart browser':
            self.worker.restart()
            return

        self.worker.close()
        sys.exit() 
Example #6
Source File: environment.py    From cassandra-medusa with Apache License 2.0 5 votes vote down vote up
def after_step(context, step):
    if BEHAVE_DEBUG_ON_ERROR and step.status == "failed":
        # -- ENTER DEBUGGER: Zoom in on failure location.
        # NOTE: Use IPython debugger, same for pdb (basic python debugger).
        import ipdb
        ipdb.post_mortem(step.exc_traceback) 
Example #7
Source File: value.py    From wextracto with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def yield_values(extract, *args, **kw):
    """ Yields ``Value`` objects extracted using ``extract``. """
    exc_info = ()

    try:
        returned = extract(*args, **kw)
        for walker in walk(returned, should_iter_unless_list):
            for value in walker:
                yield Value(value)
    except BdbQuit:
        raise
    except Exception as exc:
        exc_info = sys.exc_info()
        yield Value(exc)

    if any(exc_info) and (Value.exit_on_exc or Value.debug_on_exc):
        if Value.debug_on_exc:
            import traceback
            try:
                import ipdb as pdb
            except ImportError:
                import pdb
                assert pdb
            traceback.print_tb(exc_info[2])
            pdb.post_mortem(exc_info[2])
        else:
            reraise(exc_info[0], exc_info[1], exc_info[2]) 
Example #8
Source File: environment.py    From intake with MIT License 5 votes vote down vote up
def after_step(context, step):
    # from https://github.com/behave/behave/blob/master/docs/tutorial.rst#
    #       debug-on-error-in-case-of-step-failures
    # and https://stackoverflow.com/a/22344473/399726
    if BEHAVE_DEBUG_ON_ERROR and step.status == "failed":
        # -- ENTER DEBUGGER: Zoom in on failure location.
        # NOTE: Use IPython debugger, same for pdb (basic python debugger).
        import ipdb
        ipdb.post_mortem(step.exc_traceback) 
Example #9
Source File: debug.py    From Jacinle with MIT License 5 votes vote down vote up
def _custom_exception_hook(type, value, tb):
    if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        # we are in interactive mode or we don't have a tty-like
        # device, so we call the default hook
        sys.__excepthook__(type, value, tb)
    else:
        import traceback, ipdb
        # we are NOT in interactive mode, print the exception...
        traceback.print_exception(type, value, tb)
        # ...then start the debugger in post-mortem mode.
        ipdb.post_mortem(tb) 
Example #10
Source File: config.py    From mayo with MIT License 5 votes vote down vote up
def _excepthook(self, etype, evalue, etb):
        from IPython.core import ultratb
        from mayo.util import import_from_string
        ultratb.FormattedTB()(etype, evalue, etb)
        for exc in self.get('system.pdb.skip', []):
            exc = import_from_string(exc)
            if issubclass(etype, exc):
                sys.exit(-1)
        if self.get('system.pdb.use', True):
            import ipdb
            ipdb.post_mortem(etb) 
Example #11
Source File: environment.py    From pixelated-user-agent with GNU Affero General Public License v3.0 5 votes vote down vote up
def _debug_on_error(context, step):
    if context.config.userdata.getbool("debug"):
        try:
            import ipdb
            ipdb.post_mortem(step.exc_traceback)
        except ImportError:
            import pdb
            pdb.post_mortem(step.exc_traceback) 
Example #12
Source File: environment.py    From sismic with GNU Lesser General Public License v3.0 5 votes vote down vote up
def after_step(context, step):
    # "Given" triggers execution
    if step.step_type == 'given':
        context.interpreter.execute()

    # "When" triggers monitored execution
    if step.step_type == 'when':
        macrosteps = context.interpreter.execute()

        if not context._monitoring:
            context._monitoring = True
            context.monitored_trace = []

        context.monitored_trace.extend(macrosteps)

    # Hook to enable debugging
    if step.step_type == 'then' and step.status == 'failed' and context.config.userdata.get('debug_on_error'):
        try:
            import ipdb as pdb
        except ImportError:
            import pdb

        print('--------------------------------------------------------------')
        print('Dropping into (i)pdb.', end='\n\n')
        print('Variable context holds the current execution context of Behave')
        print('You can access the interpreter using context.interpreter, the')
        print('trace using context.trace and the monitored trace using')
        print('context.monitored_trace.')
        print('--------------------------------------------------------------')

        pdb.post_mortem(step.exc_traceback) 
Example #13
Source File: environment.py    From clusterman with Apache License 2.0 5 votes vote down vote up
def after_step(context, step):
    if BEHAVE_DEBUG_ON_ERROR and step.status == 'failed':
        import ipdb
        ipdb.post_mortem(step.exc_traceback) 
Example #14
Source File: __init__.py    From python-libmaas with GNU Affero General Public License v3.0 5 votes vote down vote up
def main(argv=sys.argv):
    program, *arguments = argv
    program = program_name_from_env(program)
    parser, options = None, None

    try:
        parser = prepare_parser(program)
        argcomplete.autocomplete(parser, exclude=("-h", "--help"))
        options = parser.parse_args(arguments)
        try:
            execute = options.execute
        except AttributeError:
            parser.error("Argument missing.")
        else:
            return execute(options)
    except KeyboardInterrupt:
        raise SystemExit(1)
    except Exception as error:
        # This is unexpected. Why? Because the CLI code raises SystemExit or
        # invokes something that raises SystemExit when it chooses to exit.
        # SystemExit does not subclass Exception, and so it would not be
        # handled here, hence this is not a deliberate exit.
        if parser is None or options is None or options.debug:
            # The user has either chosen to debug OR we crashed before/while
            # parsing arguments. Either way, let's not be terse.
            if sys.stdin.isatty() and sys.stdout.isatty():
                # We're at a fully interactive terminal so let's post-mortem.
                *_, exc_traceback = sys.exc_info()
                post_mortem(exc_traceback)
                # Exit non-zero, but quietly; dumping the traceback again on
                # the way out is confusing after doing a post-mortem.
                raise SystemExit(1)
            else:
                # Re-raise so the traceback is dumped and we exit non-zero.
                raise
        else:
            # Display a terse error message. Note that parser.error() will
            # raise SystemExit(>0) after printing its message.
            parser.error("%s" % error) 
Example #15
Source File: environment.py    From wharfee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def after_step(_, step):
    if DEBUG_ON_ERROR and step.status == 'failed':
        import ipdb
        ipdb.post_mortem(step.exc_traceback) 
Example #16
Source File: base.py    From cqparts with Apache License 2.0 4 votes vote down vote up
def debug_on_exception(func):
    """
    Opens an ``ipdb`` debugging prompt at the point of failure
    when an uncaught exception is raised.

    .. warning::

        must not be in production code... only to be used for
        debugging purposes.

    Usage::

        from base import debug_on_exception

        @debug_on_exception
        def foo(a=100):
            return 1 / a

        foo(0)

    results in an ``ipdb`` prompt::

        Traceback (most recent call last):
          File "./test.py", line 8, in wrapper
            func(*args, **kwargs)
          File "./test.py", line 19, in foo
            return 1 / a
        ZeroDivisionError: integer division or modulo by zero
        > /home/me/temp/test.py(19)foo()
             18 def foo(a=100):
        ---> 19     return 1 / a
             20

        ipdb> !a
        0
        ipdb>

    """
    def ipdb_wrapper(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except:
            import ipdb, traceback, sys
            type, value, tb = sys.exc_info()
            traceback.print_exc()
            ipdb.post_mortem(tb)
    return ipdb_wrapper


# ------------------- Core TestCase -------------------