Python bdb.BdbQuit() Examples

The following are 30 code examples of bdb.BdbQuit(). 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 bdb , or try the search function .
Example #1
Source File: awsqueryrequest.py    From canvas with BSD 3-Clause "New" or "Revised" 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 #2
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 #3
Source File: tracer.py    From qdb with Apache License 2.0 6 votes vote down vote up
def trace_dispatch(self, stackframe, event, arg):
        """
        Trace function that does some preliminary checks and then defers to
        the event handler for each type of event.
        """
        if self.quitting:
            # We were told to quit by the user, bubble this up to their code.
            return

        if self.skip_fn(stackframe.f_code.co_filename):
            # We want to skip this, don't stop but keep tracing.
            return self.trace_dispatch

        try:
            return self.super_.trace_dispatch(stackframe, event, arg)
        except BdbQuit:
            raise QdbQuit()  # Rewrap as a QdbError object. 
Example #4
Source File: test_debugging.py    From pytest with MIT License 6 votes vote down vote up
def test_raises_bdbquit_with_eoferror(testdir):
    """It is not guaranteed that DontReadFromInput's read is called."""

    p1 = testdir.makepyfile(
        """
        def input_without_read(*args, **kwargs):
            raise EOFError()

        def test(monkeypatch):
            import builtins
            monkeypatch.setattr(builtins, "input", input_without_read)
            __import__('pdb').set_trace()
        """
    )
    result = testdir.runpytest(str(p1))
    result.stdout.fnmatch_lines(["E *BdbQuit", "*= 1 failed in*"])
    assert result.ret == 1 
Example #5
Source File: test_debugging.py    From pytest with MIT License 6 votes vote down vote up
def test_doctest_set_trace_quit(self, testdir):
        p1 = testdir.makepyfile(
            """
            def function_1():
                '''
                >>> __import__('pdb').set_trace()
                '''
        """
        )
        # NOTE: does not use pytest.set_trace, but Python's patched pdb,
        #       therefore "-s" is required.
        child = testdir.spawn_pytest("--doctest-modules --pdb -s %s" % p1)
        child.expect("Pdb")
        child.sendline("q")
        rest = child.read().decode("utf8")

        assert "! _pytest.outcomes.Exit: Quitting debugger !" in rest
        assert "= no tests ran in" in rest
        assert "BdbQuit" not in rest
        assert "UNEXPECTED EXCEPTION" not in rest 
Example #6
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 #7
Source File: test_debugging.py    From pytest with MIT License 6 votes vote down vote up
def test_pdb_set_trace_interception(self, testdir):
        p1 = testdir.makepyfile(
            """
            import pdb
            def test_1():
                pdb.set_trace()
        """
        )
        child = testdir.spawn_pytest(str(p1))
        child.expect("test_1")
        child.expect("Pdb")
        child.sendline("q")
        rest = child.read().decode("utf8")
        assert "no tests ran" in rest
        assert "reading from stdin while output" not in rest
        assert "BdbQuit" not in rest
        self.flush(child) 
Example #8
Source File: test_unittest.py    From pytest with MIT License 6 votes vote down vote up
def test_BdbQuit(testdir):
    testdir.makepyfile(
        test_foo="""
        import unittest

        class MyTestCase(unittest.TestCase):
            def test_bdbquit(self):
                import bdb
                raise bdb.BdbQuit()

            def test_should_not_run(self):
                pass
    """
    )
    reprec = testdir.inline_run()
    reprec.assertoutcome(failed=1, passed=1) 
Example #9
Source File: test_debugging.py    From pytest with MIT License 5 votes vote down vote up
def test_pdb_on_BdbQuit(self, testdir, pdblist):
        rep = runpdb_and_get_report(
            testdir,
            """
            import bdb
            def test_func():
                raise bdb.BdbQuit
        """,
        )
        assert rep.failed
        assert len(pdblist) == 0 
Example #10
Source File: base_resource.py    From rotest with MIT License 5 votes vote down vote up
def enable_debug(self):
        """Wrap the resource methods with debugger."""
        debug(self.connect, ignore_exceptions=[KeyboardInterrupt, BdbQuit])
        debug(self.initialize, ignore_exceptions=[KeyboardInterrupt, BdbQuit])
        debug(self.finalize, ignore_exceptions=[KeyboardInterrupt, BdbQuit])
        debug(self.validate, ignore_exceptions=[KeyboardInterrupt, BdbQuit])
        debug(self.store_state, ignore_exceptions=[KeyboardInterrupt, BdbQuit])

        for resource in self.get_sub_resources():
            resource.enable_debug() 
Example #11
Source File: __init__.py    From OpenNIR with MIT License 5 votes vote down vote up
def handle_exception(exc_type, exc_value, exc_traceback):
    if logger is None:
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return
    if issubclass(exc_type, KeyboardInterrupt):
        logger.debug("Keyboard Interrupt", exc_info=(exc_type, exc_value, exc_traceback))
    elif issubclass(exc_type, bdb.BdbQuit):
        logger.debug("Quit", exc_info=(exc_type, exc_value, exc_traceback))
    else:
        logger.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback)) 
Example #12
Source File: main.py    From PyVideoResearch with GNU General Public License v3.0 5 votes vote down vote up
def pdbmain():
    try:
        main()
    except BdbQuit:
        sys.exit(1)
    except Exception:
        traceback.print_exc()
        print('')
        pdb.post_mortem()
        sys.exit(1) 
Example #13
Source File: battle.py    From universalSmashSystem with GNU General Public License v3.0 5 votes vote down vote up
def debugLoop(self):
        self.draw()
        pygame.display.update()
        try:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.exit_status = 1
                    self.debug_mode = False
                
                if event.type == pygame.KEYDOWN:
                    if (event.key == pygame.K_LSHIFT or event.key == pygame.K_RSHIFT):
                        self.debug_mode = False
                    elif event.key == pygame.K_TAB:
                        self.debug_console.set_trace() #Drop into the console
                    elif event.key == pygame.K_LEFT:
                        self.cameraX = -5
                    elif event.key == pygame.K_RIGHT:
                        self.cameraX = 5
                    elif event.key == pygame.K_UP:
                        self.cameraY = -5
                    elif event.key == pygame.K_DOWN:
                        self.cameraY = 5
                    elif event.key == pygame.K_z:
                        self.zoomVal = 0.01
                    elif event.key == pygame.K_x:
                        self.zoomVal = -0.01
                elif event.type == pygame.KEYUP:
                    if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                        self.cameraX = 0
                    elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                        self.cameraY = 0
                    elif event.key == pygame.K_z or event.key == pygame.K_x:
                        self.zoomVal = 0
                for cont in self.controllers:
                    cont.getInputs(event)
                
            
            self.stage.moveCamera(self.cameraX,self.cameraY)
            self.stage.zoomCamera(self.zoomVal)    
        except bdb.BdbQuit:
            pass 
Example #14
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 #15
Source File: runner.py    From pytest with MIT License 5 votes vote down vote up
def check_interactive_exception(call: "CallInfo", report: BaseReport) -> bool:
    return call.excinfo is not None and not (
        hasattr(report, "wasxfail")
        or call.excinfo.errisinstance(Skipped)
        or call.excinfo.errisinstance(bdb.BdbQuit)
    ) 
Example #16
Source File: debugger.py    From Computable with MIT License 5 votes vote down vote up
def BdbQuit_excepthook(et, ev, tb, excepthook=None):
    """Exception hook which handles `BdbQuit` exceptions.

    All other exceptions are processed using the `excepthook`
    parameter.
    """
    if et==bdb.BdbQuit:
        print('Exiting Debugger.')
    elif excepthook is not None:
        excepthook(et, ev, tb)
    else:
        # Backwards compatibility. Raise deprecation warning?
        BdbQuit_excepthook.excepthook_ori(et,ev,tb) 
Example #17
Source File: debugger.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def runexec(self, what, globs=None, locs=None):
		self.reset()
		sys.settrace(self.trace_dispatch)
		try:
			try:
				exec what in globs, locs
			except bdb.BdbQuit:
				pass
		finally:
			self.quitting = 1
			sys.settrace(None) 
Example #18
Source File: debugger.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def run(self, cmd,globals=None, locals=None, start_stepping = 1):
		if type(cmd) not in [types.StringType, types.CodeType]:
			raise TypeError("Only strings can be run")
		self.last_cmd_debugged = cmd
		if start_stepping:
			self.isInitialBreakpoint = 0
		else:
			self.isInitialBreakpoint = 1
		try:
			if globals is None:
				import __main__
				globals = __main__.__dict__
			if locals is None:
				locals = globals
			self.reset()
			self.prep_run(cmd)
			sys.settrace(self.trace_dispatch)
			if type(cmd) != types.CodeType:
				cmd = cmd+'\n'
			try:
				try:
					if start_stepping: self.skipBotFrame = SKIP_STEP
					else: self.skipBotFrame = SKIP_RUN
					if sys.version_info > (2,2):
						exec cmd in globals, locals
					else:
						_doexec(cmd, globals, locals)
				except bdb.BdbQuit:
					pass
			finally:
				self.skipBotFrame = SKIP_NONE
				self.quitting = 1
				sys.settrace(None)

		finally:
			self.done_run(cmd) 
Example #19
Source File: runner.py    From python-netsurv with MIT License 5 votes vote down vote up
def check_interactive_exception(call, report):
    return call.excinfo and not (
        hasattr(report, "wasxfail")
        or call.excinfo.errisinstance(Skipped)
        or call.excinfo.errisinstance(bdb.BdbQuit)
    ) 
Example #20
Source File: runner.py    From python-netsurv with MIT License 5 votes vote down vote up
def check_interactive_exception(call, report):
    return call.excinfo and not (
        hasattr(report, "wasxfail")
        or call.excinfo.errisinstance(Skipped)
        or call.excinfo.errisinstance(bdb.BdbQuit)
    ) 
Example #21
Source File: crashsignal.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def _handle_early_exits(self, exc):
        """Handle some special cases for the exception hook.

        Return value:
            True: Exception hook should be aborted.
            False: Continue handling exception.
        """
        exctype, _excvalue, tb = exc

        if not self._quitter.quit_status['crash']:
            log.misc.error("ARGH, there was an exception while the crash "
                           "dialog is already shown:", exc_info=exc)
            return True

        log.misc.error("Uncaught exception", exc_info=exc)

        is_ignored_exception = (exctype is bdb.BdbQuit or
                                not issubclass(exctype, Exception))

        if 'pdb-postmortem' in objects.debug_flags:
            if tb is None:
                pdb.set_trace()  # noqa: T100
            else:
                pdb.post_mortem(tb)

        if is_ignored_exception or 'pdb-postmortem' in objects.debug_flags:
            # pdb exit, KeyboardInterrupt, ...
            sys.exit(usertypes.Exit.exception)

        if threading.current_thread() != threading.main_thread():
            log.misc.error("Ignoring exception outside of main thread... "
                           "Please report this as a bug.")
            return True

        return False 
Example #22
Source File: debug.py    From recipes-py with Apache License 2.0 5 votes vote down vote up
def _debug_recipe(recipe_deps, recipe, test_data):
  """Debugs the given recipe + test case.

  Args:

    * recipe_deps (RecipeDeps)
    * recipe (Recipe)
    * test_data (TestData)
  """
  debugger = pdb.Pdb()
  for func in [recipe.global_symbols['RunSteps']]:
    debugger.set_break(
        func.func_code.co_filename,
        func.func_code.co_firstlineno,
        funcname=func.func_code.co_name)

  try:
    def dispatch_thunk(frame, event, arg):
      """Triggers 'continue' command when debugger starts."""
      val = debugger.trace_dispatch(frame, event, arg)
      debugger.set_continue()
      sys.settrace(debugger.trace_dispatch)
      return val
    debugger.reset()
    sys.settrace(dispatch_thunk)
    try:
      execute_test_case(recipe_deps, recipe.name, test_data)
    finally:
      debugger.quitting = 1
      sys.settrace(None)
  except bdb.BdbQuit:
    pass
  except Exception:  # pylint: disable=broad-except
    traceback.print_exc()
    print 'Uncaught exception. Entering post mortem debugging'
    print 'Running \'cont\' or \'step\' will restart the program'
    tback = sys.exc_info()[2]
    debugger.interaction(None, tback) 
Example #23
Source File: doctest.py    From pytest with MIT License 4 votes vote down vote up
def _init_runner_class() -> "Type[doctest.DocTestRunner]":
    import doctest

    class PytestDoctestRunner(doctest.DebugRunner):
        """
        Runner to collect failures.  Note that the out variable in this case is
        a list instead of a stdout-like object
        """

        def __init__(
            self,
            checker: Optional[doctest.OutputChecker] = None,
            verbose: Optional[bool] = None,
            optionflags: int = 0,
            continue_on_failure: bool = True,
        ) -> None:
            doctest.DebugRunner.__init__(
                self, checker=checker, verbose=verbose, optionflags=optionflags
            )
            self.continue_on_failure = continue_on_failure

        def report_failure(
            self, out, test: "doctest.DocTest", example: "doctest.Example", got: str,
        ) -> None:
            failure = doctest.DocTestFailure(test, example, got)
            if self.continue_on_failure:
                out.append(failure)
            else:
                raise failure

        def report_unexpected_exception(
            self,
            out,
            test: "doctest.DocTest",
            example: "doctest.Example",
            exc_info: "Tuple[Type[BaseException], BaseException, types.TracebackType]",
        ) -> None:
            if isinstance(exc_info[1], OutcomeException):
                raise exc_info[1]
            if isinstance(exc_info[1], bdb.BdbQuit):
                outcomes.exit("Quitting debugger")
            failure = doctest.UnexpectedException(test, example, exc_info)
            if self.continue_on_failure:
                out.append(failure)
            else:
                raise failure

    return PytestDoctestRunner 
Example #24
Source File: doctest_driver.py    From razzy-spinner with GNU General Public License v3.0 4 votes vote down vote up
def debug(self, test, pm=False):
        self.test = test

        # Save the old stdout
        self.save_stdout = sys.stdout

        # Convert the source docstring to a script.
        script = self._script_from_examples(test.docstring)

        # Create a debugger.
        debugger = _OutputRedirectingPdb(sys.stdout)

        # Patch pdb.set_trace to restore sys.stdout during interactive
        # debugging (so it's not still redirected to self._fakeout).
        save_set_trace = pdb.set_trace
        pdb.set_trace = debugger.set_trace

        # Write the script to a temporary file.  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(script)
        f.close()

        # Set up the globals
        test.globs['CHECK_OUTPUT'] = self._check_output
        test.globs['CHECK_EXCEPTION'] = self._check_exception
        test.globs['__print__'] = self._print_if_not_none
        test.globs['__set_trace__'] = debugger.set_trace
        test.globs['__examples__'] = self.test.examples
        try:
            if pm is False:
                debugger.run("execfile(%r)" % srcfilename,
                             test.globs, test.globs)
            else:
                try:
                    sys.stdout = _SpoofOut()
                    try:
                        execfile(srcfilename, test.globs)
                    except bdb.BdbQuit:
                        return
                    except:
                        sys.stdout = self.save_stdout
                        exc_info = sys.exc_info()
                        exc_msg = traceback.format_exception_only(
                            exc_info[0], exc_info[1])[-1]
                        self.save_stdout.write(self.runner.DIVIDER+'\n')
                        self.save_stdout.write('Unexpected exception:\n' +
                                               _indent(exc_msg))
                        raise
                        #self.post_mortem(debugger, exc_info[2])
                finally:
                    sys.stdout = self.save_stdout
        finally:
            sys.set_trace = save_set_trace
            os.remove(srcfilename) 
Example #25
Source File: debugger.py    From Computable with MIT License 4 votes vote down vote up
def __init__(self,colors=None):
        """Create a local debugger instance.

        :Parameters:

          - `colors` (None): a string containing the name of the color scheme to
        use, it must be one of IPython's valid color schemes.  If not given, the
        function will default to the current IPython scheme when running inside
        IPython, and to 'NoColor' otherwise.

        Usage example:

        from IPython.core.debugger import Tracer; debug_here = Tracer()

        ... later in your code
        debug_here()  # -> will open up the debugger at that point.

        Once the debugger activates, you can use all of its regular commands to
        step through code, set breakpoints, etc.  See the pdb documentation
        from the Python standard library for usage details.
        """

        ip = get_ipython()
        if ip is None:
            # Outside of ipython, we set our own exception hook manually
            sys.excepthook = functools.partial(BdbQuit_excepthook,
                                               excepthook=sys.excepthook)
            def_colors = 'NoColor'
            try:
                # Limited tab completion support
                import readline
                readline.parse_and_bind('tab: complete')
            except ImportError:
                pass
        else:
            # In ipython, we use its custom exception handler mechanism
            def_colors = ip.colors
            ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)

        if colors is None:
            colors = def_colors

        # The stdlib debugger internally uses a modified repr from the `repr`
        # module, that limits the length of printed strings to a hardcoded
        # limit of 30 characters.  That much trimming is too aggressive, let's
        # at least raise that limit to 80 chars, which should be enough for
        # most interactive uses.
        try:
            from repr import aRepr
            aRepr.maxstring = 80
        except:
            # This is only a user-facing convenience, so any error we encounter
            # here can be warned about but can be otherwise ignored.  These
            # printouts will tell us about problems if this API changes
            import traceback
            traceback.print_exc()

        self.debugger = Pdb(colors) 
Example #26
Source File: spydercustomize.py    From spyder-kernels with MIT License 4 votes vote down vote up
def exec_code(code, filename, ns_globals, ns_locals=None, post_mortem=False):
    """Execute code and display any exception."""
    global SHOW_INVALID_SYNTAX_MSG

    if PY2:
        filename = encode(filename)
        code = encode(code)

    ipython_shell = get_ipython()
    is_ipython = os.path.splitext(filename)[1] == '.ipy'
    try:
        if not is_ipython:
            # TODO: remove the try-except and let the SyntaxError raise
            # Because there should not be ipython code in a python file
            try:
                compiled = compile(code, filename, 'exec')
            except SyntaxError as e:
                try:
                    compiled = compile(transform_cell(code), filename, 'exec')
                except SyntaxError:
                    if PY2:
                        raise e
                    else:
                        # Need to call exec to avoid Syntax Error in Python 2.
                        # TODO: remove exec when dropping Python 2 support.
                        exec("raise e from None")
                else:
                    if SHOW_INVALID_SYNTAX_MSG:
                        _print(
                            "\nWARNING: This is not valid Python code. "
                            "If you want to use IPython magics, "
                            "flexible indentation, and prompt removal, "
                            "please save this file with the .ipy extension. "
                            "This will be an error in a future version of "
                            "Spyder.\n")
                        SHOW_INVALID_SYNTAX_MSG = False
        else:
            compiled = compile(transform_cell(code), filename, 'exec')

        exec(compiled, ns_globals, ns_locals)
    except SystemExit as status:
        # ignore exit(0)
        if status.code:
            ipython_shell.showtraceback(exception_only=True)
    except BaseException as error:
        if (isinstance(error, bdb.BdbQuit)
                and ipython_shell.kernel._pdb_obj):
            # Ignore BdbQuit if we are debugging, as it is expected.
            ipython_shell.kernel._pdb_obj = None
        elif post_mortem and isinstance(error, Exception):
            error_type, error, tb = sys.exc_info()
            post_mortem_excepthook(error_type, error, tb)
        else:
            # We ignore the call to exec
            ipython_shell.showtraceback(tb_offset=1) 
Example #27
Source File: doctest_driver.py    From luscan-devel with GNU General Public License v2.0 4 votes vote down vote up
def debug(self, test, pm=False):
        self.test = test

        # Save the old stdout
        self.save_stdout = sys.stdout

        # Convert the source docstring to a script.
        script = self._script_from_examples(test.docstring)

        # Create a debugger.
        debugger = _OutputRedirectingPdb(sys.stdout)

        # Patch pdb.set_trace to restore sys.stdout during interactive
        # debugging (so it's not still redirected to self._fakeout).
        save_set_trace = pdb.set_trace
        pdb.set_trace = debugger.set_trace

        # Write the script to a temporary file.  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(script)
        f.close()

        # Set up the globals
        test.globs['CHECK_OUTPUT'] = self._check_output
        test.globs['CHECK_EXCEPTION'] = self._check_exception
        test.globs['__print__'] = self._print_if_not_none
        test.globs['__set_trace__'] = debugger.set_trace
        test.globs['__examples__'] = self.test.examples
        try:
            if pm is False:
                debugger.run("execfile(%r)" % srcfilename,
                             test.globs, test.globs)
            else:
                try:
                    sys.stdout = _SpoofOut()
                    try:
                        execfile(srcfilename, test.globs)
                    except bdb.BdbQuit:
                        return
                    except:
                        sys.stdout = self.save_stdout
                        exc_info = sys.exc_info()
                        exc_msg = traceback.format_exception_only(
                            exc_info[0], exc_info[1])[-1]
                        self.save_stdout.write(self.runner.DIVIDER+'\n')
                        self.save_stdout.write('Unexpected exception:\n' +
                                               _indent(exc_msg))
                        raise
                        #self.post_mortem(debugger, exc_info[2])
                finally:
                    sys.stdout = self.save_stdout
        finally:
            sys.set_trace = save_set_trace
            os.remove(srcfilename) 
Example #28
Source File: __init__.py    From epdb with MIT License 4 votes vote down vote up
def __call__(self, typ, value, tb):
        if typ is bdb.BdbQuit:
            sys.exit(1)

        sys.excepthook = sys.__excepthook__
        if typ == KeyboardInterrupt and not self.debugCtrlC:
            sys.exit(1)

        out = StringIO()
        formatTrace(typ, value, tb, stream=out, withLocals=False)
        out.write("\nFull stack:\n")
        formatTrace(typ, value, tb, stream=out, withLocals=True)
        out.seek(0)
        tbString = out.read()
        del out

        if self.syslog is not None:
            self.syslog("command failed\n%s", tbString)

        if self.debug:
            formatTrace(typ, value, tb, stream=sys.stderr, withLocals=False)
            if sys.stdout.isatty() and sys.stdin.isatty():
                post_mortem(tb, typ, value)
            else:
                sys.exit(1)
        elif log.getVerbosity() is logging.DEBUG:
            log.debug(tbString)
        else:
            sys.argv[0] = os.path.normpath(sys.argv[0])
            while tb.tb_next:
                tb = tb.tb_next
            lineno = tb.tb_frame.f_lineno
            filename = tb.tb_frame.f_code.co_filename
            tmpfd, stackfile = tempfile.mkstemp('.txt', self.prefix)
            os.write(tmpfd, tbString)
            os.close(tmpfd)

            sys.stderr.write(self.error % dict(command=' '.join(sys.argv),
                                               filename=filename,
                                               lineno=lineno,
                                               errtype=typ.__name__,
                                               errmsg=value,
                                               stackfile=stackfile)) 
Example #29
Source File: test_pdb.py    From pdbpp with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def runpdb(func, input, terminal_size=None):
    oldstdin = sys.stdin
    oldstdout = sys.stdout
    oldstderr = sys.stderr
    # Use __dict__ to avoid class descriptor (staticmethod).
    old_get_terminal_size = pdbpp.Pdb.__dict__["get_terminal_size"]

    if sys.version_info < (3, ):
        text_type = unicode  # noqa: F821
    else:
        text_type = str

    class MyBytesIO(BytesIO):
        """write accepts unicode or bytes"""

        encoding = 'ascii'

        def __init__(self, encoding='utf-8'):
            self.encoding = encoding

        def write(self, msg):
            if isinstance(msg, text_type):
                msg = msg.encode(self.encoding)
            super(MyBytesIO, self).write(msg)

        def get_unicode_value(self):
            return self.getvalue().decode(self.encoding).replace(
                pdbpp.CLEARSCREEN, "<CLEARSCREEN>\n"
            ).replace(chr(27), "^[")

    # Use a predictable terminal size.
    if terminal_size is None:
        terminal_size = (80, 24)
    pdbpp.Pdb.get_terminal_size = staticmethod(lambda: terminal_size)
    try:
        sys.stdin = FakeStdin(input)
        sys.stdout = stdout = MyBytesIO()
        sys.stderr = stderr = MyBytesIO()
        func()
    except InnerTestException:
        pass
    except bdb.BdbQuit:
        print("!! Received unexpected bdb.BdbQuit !!")
    except Exception:
        # Make it available for pytests output capturing.
        print(stdout.get_unicode_value(), file=oldstdout)
        raise
    finally:
        sys.stdin = oldstdin
        sys.stdout = oldstdout
        sys.stderr = oldstderr
        pdbpp.Pdb.get_terminal_size = old_get_terminal_size

    stderr = stderr.get_unicode_value()
    if stderr:
        # Make it available for pytests output capturing.
        print(stdout.get_unicode_value())
        raise AssertionError("Unexpected output on stderr: %s" % stderr)

    return stdout.get_unicode_value().splitlines() 
Example #30
Source File: console.py    From python-sploitkit with GNU Affero General Public License v3.0 4 votes vote down vote up
def run(self, cmd, abort=False):
        """ Run a framework console command. """
        # assign tokens (or abort if tokens' split gives [])
        tokens = self._get_tokens(cmd)
        try:
            name, args = tokens[0], tokens[1:]
        except IndexError:
            return True
        # get the command singleton instance (or abort if name not in
        #  self.commands) ; if command arguments should not be split, adapt args
        try:
            obj = self.commands[name]._instance
        except KeyError:
            return True
        # now handle the command (and its validation if existing)
        try:
            if hasattr(obj, "validate"):
                obj.validate(*args)
            if name != "run" or self._run_if_defined("prerun"):
                obj.run(*args)
                if name == "run":
                    self._run_if_defined("postrun")
            return True
        except BdbQuit:  # when using pdb.set_trace()
            return True
        except ConsoleDuplicate as e:
            # pass the higher console instance attached to the exception raised
            #  from within a command's .run() execution to console's .start(),
            #  keeping the current command to be reexecuted
            raise ConsoleDuplicate(e.current, e.higher,
                                   cmd if e.cmd is None else e.cmd)
        except ConsoleExit:
            return False
        except ValueError as e:
            if str(e).startswith("invalid width ") and \
               str(e).endswith(" (must be > 0)"):
                self.logger.warning("Cannot display ; terminal width too low")
            else:
                (self.logger.exception if self.config.option('DEBUG').value \
                 else self.logger.failure)(e)
            return abort is False
        except Exception as e:
            self.logger.exception(e)
            return abort is False
        finally:
            gc.collect()