Python pdb.post_mortem() Examples

The following are 30 code examples of pdb.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 pdb , or try the search function .
Example #1
Source File: webserver.py    From beancount-import with GNU General Public License v2.0 6 votes vote down vote up
def send_state_update(self):
        try:
            update = dict()
            new_state = self.application.current_state
            new_state_generation = self.application.current_state_generation
            prev_state = self.prev_state
            prev_state_generation = self.prev_state_generation
            for k, v in new_state.items():
                generation = new_state_generation[k]
                if prev_state_generation.get(k) != generation:
                    prev_state_generation[k] = generation
                    update[k] = v
            for k, v in prev_state.items():
                if k not in new_state:
                    update[k] = None
            if len(update) > 0:
                self.write_message(
                    json.dumps(
                        dict(type='state_update', state=update),
                        default=json_encode_state))
                prev_state.update(update)
        except:
            traceback.print_exc()
            pdb.post_mortem() 
Example #2
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 #3
Source File: gradebuilder.py    From regolith with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def render(self, tname, fname, **kwargs):
        template = self.env.get_template(tname)
        ctx = dict(self.gtx)
        ctx.update(kwargs)
        ctx["rc"] = ctx.get("rc", self.rc)
        ctx["static"] = ctx.get(
            "static", os.path.relpath("static", os.path.dirname(fname))
        )
        ctx["root"] = ctx.get(
            "root", os.path.relpath("/", os.path.dirname(fname))
        )
        try:
            result = template.render(ctx)
        except:
            type, value, tb = sys.exc_info()
            traceback.print_exc()
            pdb.post_mortem(tb)
        with open(os.path.join(self.bldir, fname), "wt", encoding='utf-8'
                  ) as f:
            f.write(result) 
Example #4
Source File: cmd2plus.py    From OpenTrader with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #5
Source File: post_mortem_debug.py    From tacker with Apache License 2.0 6 votes vote down vote up
def exception_handler(exc_info):
    """Exception handler enabling post-mortem debugging.

    A class extending testtools.TestCase can add this handler in setUp():

        self.addOnException(post_mortem_debug.exception_handler)

    When an exception occurs, the user will be dropped into a pdb
    session in the execution environment of the failure.

    Frames associated with the testing framework are excluded so that
    the post-mortem session for an assertion failure will start at the
    assertion call (e.g. self.assertTrue) rather than the framework code
    that raises the failure exception (e.g. the assertTrue method).
    """
    tb = exc_info[2]
    ignored_traceback = get_ignored_traceback(tb)
    if ignored_traceback:
        tb = FilteredTraceback(tb, ignored_traceback)
    traceback.print_exception(exc_info[0], exc_info[1], tb)
    pdb.post_mortem(tb) 
Example #6
Source File: debughelper.py    From dpu-utils with MIT License 6 votes vote down vote up
def run_and_debug(func: Callable[[], None], enable_debugging: bool) -> None:
    """
    A wrapper around a running script that triggers the debugger in case of an uncaught exception.
    
    For example, this can be used as:
    ```
    if __name__ == '__main__':
        args = docopt(__doc__)
        run_and_debug(lambda: run(args), args['--debug'])
    ```
    """
    try:
        func()
    except:
        if enable_debugging:
            _, value, tb = sys.exc_info()
            traceback.print_exc()
            pdb.post_mortem(tb)
        else:
            raise 
Example #7
Source File: session.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def _HandleRunPluginException(self, ui_renderer, e):
        """Handle all exceptions thrown by logging to the console."""

        if isinstance(e, plugin.InvalidArgs):
            self.logging.fatal("Invalid Args: %s" % e)

        elif isinstance(e, plugin.PluginError):
            self.logging.fatal(str(e))

        elif isinstance(e, (KeyboardInterrupt, plugin.Abort)):
            logging.error("Aborted\r\n")

        else:
            error_status = traceback.format_exc()

            # Report the error to the renderer.
            self.logging.fatal(error_status)

            # If anything goes wrong, we break into a debugger here.
            if self.GetParameter("debug"):
                pdb.post_mortem(sys.exc_info()[2])

            # This method is called from the exception handler - this bare raise
            # will preserve backtraces.
            raise  # pylint: disable=misplaced-bare-raise 
Example #8
Source File: opt.py    From D-VAE with MIT License 6 votes vote down vote up
def warn(exc, nav, repl_pairs, local_opt, node):
        """
        Failure_callback for NavigatorOptimizer: print traceback.

        """
        if config.on_opt_error != 'ignore':
            _logger.error("Optimization failure due to: %s" % str(local_opt))
            _logger.error("node: %s" % str(node))
            _logger.error("TRACEBACK:")
            _logger.error(traceback.format_exc())
        if config.on_opt_error == 'pdb':
            pdb.post_mortem(sys.exc_info()[2])
        elif isinstance(exc, AssertionError) or config.on_opt_error == 'raise':
            # We always crash on AssertionError because something may be
            # seriously wrong if such an exception is raised.
            raise exc 
Example #9
Source File: utils.py    From senpy with Apache License 2.0 6 votes vote down vote up
def easy_test(plugin_list=None, debug=True):
    logger.setLevel(logging.DEBUG)
    logging.getLogger().setLevel(logging.INFO)
    try:
        if not plugin_list:
            import __main__
            logger.info('Loading classes from {}'.format(__main__))
            from . import plugins
            plugin_list = plugins.from_module(__main__)
        plugin_list = list(plugin_list)
        for plug in plugin_list:
            plug.test()
            plug.log.info('My tests passed!')
        logger.info('All tests passed for {} plugins!'.format(len(plugin_list)))
    except Exception:
        if not debug:
            raise
        pdb.post_mortem() 
Example #10
Source File: cli.py    From bioconda-utils with MIT License 6 votes vote down vote up
def enable_debugging():
    """Adds the paremeter ``--pdb`` (or ``-P``) to enable dropping into PDB"""
    def decorator(func):
        @arg('-P', '--pdb', help="Drop into debugger on exception")
        @utils.wraps(func)
        def wrapper(*args, pdb=False, **kwargs):
            try:
                func(*args, **kwargs)
            except Exception as e:
                logger.exception("Dropping into debugger")
                if pdb:
                    import pdb
                    pdb.post_mortem()
                else:
                    raise
        return wrapper
    return decorator 
Example #11
Source File: utils.py    From SpatioTemporalSegmentation with MIT License 6 votes vote down vote up
def debug_on():
  import sys
  import pdb
  import functools
  import traceback

  def decorator(f):

    @functools.wraps(f)
    def wrapper(*args, **kwargs):
      try:
        return f(*args, **kwargs)
      except Exception:
        info = sys.exc_info()
        traceback.print_exception(*info)
        pdb.post_mortem(info[2])

    return wrapper

  return decorator 
Example #12
Source File: awsqueryrequest.py    From aws-extender with MIT License 6 votes vote down vote up
def boto_except_hook(debugger_flag, debug_flag):
    def excepthook(typ, value, tb):
        if typ is bdb.BdbQuit:
            sys.exit(1)
        sys.excepthook = sys.__excepthook__

        if debugger_flag and sys.stdout.isatty() and sys.stdin.isatty():
            if debugger.__name__ == 'epdb':
                debugger.post_mortem(tb, typ, value)
            else:
                debugger.post_mortem(tb)
        elif debug_flag:
            print(traceback.print_tb(tb))
            sys.exit(1)
        else:
            print(value)
            sys.exit(1)

    return excepthook 
Example #13
Source File: testutils.py    From OpenRAM with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def debugTestRunner(post_mortem=None):
    """unittest runner doing post mortem debugging on failing tests"""
    if post_mortem is None and not OPTS.purge_temp:
        post_mortem = pdb.post_mortem
    class DebugTestResult(unittest.TextTestResult):
        def addError(self, test, err):
            # called before tearDown()
            traceback.print_exception(*err)
            if post_mortem:
                post_mortem(err[2])
            super(DebugTestResult, self).addError(test, err)
        def addFailure(self, test, err):
            traceback.print_exception(*err)
            if post_mortem:            
                post_mortem(err[2])
            super(DebugTestResult, self).addFailure(test, err)
    return unittest.TextTestRunner(resultclass=DebugTestResult) 
Example #14
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 #15
Source File: tools.py    From OpenTrader with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #16
Source File: webserver.py    From beancount-import with GNU General Public License v2.0 6 votes vote down vote up
def _handle_reconciler_loaded(self, loaded_future):
        try:
            loaded_reconciler = loaded_future.result()
            generation = self.next_generation()
            self.set_state(
                errors=(generation, len(loaded_reconciler.errors)),
                invalid=(generation, len(loaded_reconciler.invalid_references)),
                accounts=sorted(loaded_reconciler.editor.accounts.keys()),
                journal_filenames=sorted(
                    list(loaded_reconciler.editor.journal_filenames)))
            self.current_errors = loaded_reconciler.errors
            self.current_invalid = loaded_reconciler.invalid_references
            self.start_check_modification_observer(loaded_reconciler)
            self.get_next_candidates(new_pending=True)
        except:
            traceback.print_exc()
            pdb.post_mortem() 
Example #17
Source File: opt.py    From attention-lvcsr with MIT License 6 votes vote down vote up
def warn(exc, nav, repl_pairs, local_opt, node):
        """
        Failure_callback for NavigatorOptimizer: print traceback.

        """
        if config.on_opt_error != 'ignore':
            _logger.error("Optimization failure due to: %s" % str(local_opt))
            _logger.error("node: %s" % str(node))
            _logger.error("TRACEBACK:")
            _logger.error(traceback.format_exc())
        if config.on_opt_error == 'pdb':
            pdb.post_mortem(sys.exc_info()[2])
        elif isinstance(exc, AssertionError) or config.on_opt_error == 'raise':
            # We always crash on AssertionError because something may be
            # seriously wrong if such an exception is raised.
            raise exc 
Example #18
Source File: webserver.py    From beancount-import with GNU General Public License v2.0 6 votes vote down vote up
def handle_select_candidate(self, msg):
        try:
            if (self.next_candidates is not None and msg['generation'] ==
                    self.current_state['candidates_generation']):
                index = msg['index']
                if index >= 0 and index < len(self.next_candidates.candidates):
                    candidate = self.next_candidates.candidates[index]
                    ignore = msg.get('ignore', None) is True
                    result = self.reconciler.loaded_future.result(
                    ).accept_candidate(
                        candidate,
                        ignore=ignore,
                    )
                    self._notify_modified_files(result.modified_filenames)
                    self.get_next_candidates(new_pending=True)
                    return result.new_entries
        except:
            traceback.print_exc()
            print('got error')
            pdb.post_mortem() 
Example #19
Source File: failure.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _debuginit(self, exc_value=None, exc_type=None, exc_tb=None,
               captureVars=False,
               Failure__init__=Failure.__init__):
    """
    Initialize failure object, possibly spawning pdb.
    """
    if (exc_value, exc_type, exc_tb) == (None, None, None):
        exc = sys.exc_info()
        if not exc[0] == self.__class__ and DO_POST_MORTEM:
            try:
                strrepr = str(exc[1])
            except:
                strrepr = "broken str"
            print("Jumping into debugger for post-mortem of exception '%s':" %
                  (strrepr,))
            import pdb
            pdb.post_mortem(exc[2])
    Failure__init__(self, exc_value, exc_type, exc_tb, captureVars) 
Example #20
Source File: script.py    From ldap2pg with PostgreSQL License 6 votes vote down vote up
def main():
    config = Configuration()
    debug = False

    try:
        debug = config.bootstrap(environ=os.environ)
        if debug:
            logger.debug("Debug mode enabled.")
        exit(wrapped_main(config))
    except pdb.bdb.BdbQuit:
        logger.info("Graceful exit from debugger.")
    except UserError as e:
        logger.critical("%s", e)
        exit(e.exit_code)
    except Exception:
        logger.exception('Unhandled error:')
        if debug and sys.stdout.isatty():
            logger.debug("Dropping in debugger.")
            pdb.post_mortem(sys.exc_info()[2])
        else:
            logger.error(
                "Please file an issue at "
                "https://github.com/dalibo/ldap2pg/issues with full log.",
            )
    exit(os.EX_SOFTWARE) 
Example #21
Source File: utils.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_pdb_trace(pm=False):
    """Start the Python debugger when robotframework is running.

    This makes sure that pdb can use stdin/stdout even though
    robotframework has redirected I/O.
    """
    import sys
    import pdb

    for attr in ("stdin", "stdout", "stderr"):
        setattr(sys, attr, getattr(sys, "__%s__" % attr))
    if pm:
        # Post-mortem debugging of an exception
        pdb.post_mortem()
    else:
        pdb.set_trace()


# This is a list of user actions that are likely to trigger
# Aura actions and/or XHRs. We'll add a step to wait for
# in-flight XHRs to complete after these commands. 
Example #22
Source File: debug.py    From forge with GNU General Public License v3.0 6 votes vote down vote up
def debug_on(*exceptions):
    """Adapted from https://stackoverflow.com/questions/18960242/is-it-possible-to-automatically-break-into-the-debugger-when-a-exception-is-thro/18962528
    """

    if not exceptions:
        exceptions = (AssertionError,)

    def decorator(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            try:
                return f(*args, **kwargs)

            except exceptions as err:
                last_traceback = sys.exc_info()[2]
                traceback.print_tb(last_traceback)
                print(err)
                pdb.post_mortem(last_traceback)

        return wrapper

    return decorator 
Example #23
Source File: utilities.py    From vivarium with GNU General Public License v3.0 6 votes vote down vote up
def handle_exceptions(func: Callable, logger: Any, with_debugger: bool) -> Callable:
    """Drops a user into an interactive debugger if func raises an error."""

    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except (BdbQuit, KeyboardInterrupt):
            raise
        except Exception as e:
            logger.exception("Uncaught exception {}".format(e))
            if with_debugger:
                import pdb
                import traceback
                traceback.print_exc()
                pdb.post_mortem()
            else:
                raise

    return wrapped 
Example #24
Source File: test_failure.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def setUp(self):
        """
        Override pdb.post_mortem so we can make sure it's called.
        """
        # Make sure any changes we make are reversed:
        post_mortem = pdb.post_mortem
        if _shouldEnableNewStyle:
            origInit = failure.Failure.__init__
        else:
            origInit = failure.Failure.__dict__['__init__']
        def restore():
            pdb.post_mortem = post_mortem
            if _shouldEnableNewStyle:
                failure.Failure.__init__ = origInit
            else:
                failure.Failure.__dict__['__init__'] = origInit
        self.addCleanup(restore)

        self.result = []
        pdb.post_mortem = self.result.append
        failure.startDebugMode() 
Example #25
Source File: failure.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _debuginit(self, exc_value=None, exc_type=None, exc_tb=None,
               captureVars=False,
               Failure__init__=Failure.__init__):
    """
    Initialize failure object, possibly spawning pdb.
    """
    if (exc_value, exc_type, exc_tb) == (None, None, None):
        exc = sys.exc_info()
        if not exc[0] == self.__class__ and DO_POST_MORTEM:
            try:
                strrepr = str(exc[1])
            except:
                strrepr = "broken str"
            print("Jumping into debugger for post-mortem of exception '%s':" % (strrepr,))
            import pdb
            pdb.post_mortem(exc[2])
    Failure__init__(self, exc_value, exc_type, exc_tb, captureVars) 
Example #26
Source File: __main__.py    From pydeface with MIT License 6 votes vote down vote up
def setup_exceptionhook():
    """
    Overloads default sys.excepthook with our exceptionhook handler.

    If interactive, our exceptionhook handler will invoke pdb.post_mortem;
    if not interactive, then invokes default handler.
    """
    def _pdb_excepthook(type, value, tb):
        if is_interactive():
            import traceback
            import pdb
            traceback.print_exception(type, value, tb)
            # print()
            pdb.post_mortem(tb)
        else:
            lgr.warn(
                "We cannot setup exception hook since not in interactive mode")

    sys.excepthook = _pdb_excepthook 
Example #27
Source File: cci.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def show_debug_info():
    """Displays the traceback and opens pdb"""
    traceback.print_exc()
    pdb.post_mortem() 
Example #28
Source File: doctest.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def debug_script(src, pm=False, globs=None):
    "Debug a test script.  `src` is the script, as a string."
    import pdb

    # Note that tempfile.NameTemporaryFile() cannot be used.  As the
    # docs say, a file so created cannot be opened by name a second time
    # on modern Windows boxes, and execfile() needs to open it.
    srcfilename = tempfile.mktemp(".py", "doctestdebug")
    f = open(srcfilename, 'w')
    f.write(src)
    f.close()

    try:
        if globs:
            globs = globs.copy()
        else:
            globs = {}

        if pm:
            try:
                execfile(srcfilename, globs, globs)
            except:
                print sys.exc_info()[1]
                pdb.post_mortem(sys.exc_info()[2])
        else:
            # Note that %r is vital here.  '%s' instead can, e.g., cause
            # backslashes to get treated as metacharacters on Windows.
            pdb.run("execfile(%r)" % srcfilename, globs, globs)

    finally:
        os.remove(srcfilename) 
Example #29
Source File: __init__.py    From virlutils with MIT License 5 votes vote down vote up
def debug_on(*exceptions):
    if not exceptions:
        exceptions = (AssertionError, )

    def decorator(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except exceptions:
                info = sys.exc_info()
                traceback.print_exception(*info)
                pdb.post_mortem(info[2])
        return wrapper
    return decorator 
Example #30
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])