Python sys.breakpointhook() Examples

The following are 13 code examples of sys.breakpointhook(). 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 sys , or try the search function .
Example #1
Source File: base_cdm_dbg.py    From codimension with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, dbgClient):
        self._dbgClient = dbgClient

        # Some informations about the thread
        self.isMainThread = False
        self.quitting = False
        self.id = -1
        self.name = ''

        self.tracePythonLibs(0)

        # Special handling of a recursion error
        self.skipFrames = 0

        self.isBroken = False
        self.cFrame = None

        # current frame we are at
        self.currentFrame = None

        # frames, where we want to stop or release debugger
        self.stopframe = None
        self.returnframe = None
        self.stop_everywhere = False

        self.__recursionDepth = -1
        self.setRecursionDepth(inspect.currentframe())

        # background task to periodicaly check for client interactions
        self.eventPollFlag = False
        self.timer = _thread.start_new_thread(self.__eventPollTimer, ())

        # provide a hook to perform a hard breakpoint
        # Use it like this:
        # if hasattr(sys, 'breakpoint): sys.breakpoint()
        sys.breakpoint = self.set_trace
        if sys.version_info[:2] >= (3, 7):
            sys.breakpointhook = self.set_trace 
Example #2
Source File: sitecustomize.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def install_breakpointhook():
    def custom_sitecustomize_breakpointhook(*args, **kwargs):
        import os
        hookname = os.getenv('PYTHONBREAKPOINT')
        if (
               hookname is not None 
               and len(hookname) > 0 
               and hasattr(sys, '__breakpointhook__')
               and sys.__breakpointhook__ != custom_sitecustomize_breakpointhook
            ):
            sys.__breakpointhook__(*args, **kwargs)
        else:
            sys.path.append(os.path.dirname(os.path.dirname(__file__)))
            import pydevd
            kwargs.setdefault('stop_at_frame', sys._getframe().f_back)
            pydevd.settrace(*args, **kwargs)

    if sys.version_info[0:2] >= (3, 7):
        # There are some choices on how to provide the breakpoint hook. Namely, we can provide a 
        # PYTHONBREAKPOINT which provides the import path for a method to be executed or we
        # can override sys.breakpointhook.
        # pydevd overrides sys.breakpointhook instead of providing an environment variable because
        # it's possible that the debugger starts the user program but is not available in the 
        # PYTHONPATH (and would thus fail to be imported if PYTHONBREAKPOINT was set to pydevd.settrace).
        # Note that the implementation still takes PYTHONBREAKPOINT in account (so, if it was provided
        # by someone else, it'd still work).
        sys.breakpointhook = custom_sitecustomize_breakpointhook
    else:
        if sys.version_info[0] >= 3:
            import builtins as __builtin__ # Py3
        else:
            import __builtin__

        # In older versions, breakpoint() isn't really available, so, install the hook directly
        # in the builtins.
        __builtin__.breakpoint = custom_sitecustomize_breakpointhook
        sys.__breakpointhook__ = custom_sitecustomize_breakpointhook

# Install the breakpoint hook at import time. 
Example #3
Source File: test_debugging.py    From pytest with MIT License 5 votes vote down vote up
def test_sys_breakpointhook_configure_and_unconfigure(self, testdir, arg):
        """
        Test that sys.breakpointhook is set to the custom Pdb class once configured, test that
        hook is reset to system value once pytest has been unconfigured
        """
        testdir.makeconftest(
            """
            import sys
            from pytest import hookimpl
            from _pytest.debugging import pytestPDB

            def pytest_configure(config):
                config._cleanup.append(check_restored)

            def check_restored():
                assert sys.breakpointhook == sys.__breakpointhook__

            def test_check():
                assert sys.breakpointhook == pytestPDB.set_trace
        """
        )
        testdir.makepyfile(
            """
            def test_nothing(): pass
        """
        )
        args = (arg,) if arg else ()
        result = testdir.runpytest_subprocess(*args)
        result.stdout.fnmatch_lines(["*1 passed in *"]) 
Example #4
Source File: test_debugging.py    From pytest with MIT License 5 votes vote down vote up
def test_environ_custom_class(self, testdir, custom_debugger_hook, arg):
        testdir.makeconftest(
            """
            import os
            import sys

            os.environ['PYTHONBREAKPOINT'] = '_pytest._CustomDebugger.set_trace'

            def pytest_configure(config):
                config._cleanup.append(check_restored)

            def check_restored():
                assert sys.breakpointhook == sys.__breakpointhook__

            def test_check():
                import _pytest
                assert sys.breakpointhook is _pytest._CustomDebugger.set_trace
        """
        )
        testdir.makepyfile(
            """
            def test_nothing(): pass
        """
        )
        args = (arg,) if arg else ()
        result = testdir.runpytest_subprocess(*args)
        result.stdout.fnmatch_lines(["*1 passed in *"]) 
Example #5
Source File: backend.py    From thonny with MIT License 5 votes vote down vote up
def _execute_prepared_user_code(self, statements, global_vars):
        try:
            sys.settrace(self._trace)
            if hasattr(sys, "breakpointhook"):
                old_breakpointhook = sys.breakpointhook
                sys.breakpointhook = self._breakpointhook

            return super()._execute_prepared_user_code(statements, global_vars)
        finally:
            sys.settrace(None)
            if hasattr(sys, "breakpointhook"):
                sys.breakpointhook = old_breakpointhook 
Example #6
Source File: test_builtin.py    From android_universal with MIT License 5 votes vote down vote up
def setUp(self):
        # These tests require a clean slate environment.  For example, if the
        # test suite is run with $PYTHONBREAKPOINT set to something else, it
        # will mess up these tests.  Similarly for sys.breakpointhook.
        # Cleaning the slate here means you can't use breakpoint() to debug
        # these tests, but I think that's okay.  Just use pdb.set_trace() if
        # you must.
        self.resources = ExitStack()
        self.addCleanup(self.resources.close)
        self.env = self.resources.enter_context(EnvironmentVarGuard())
        del self.env['PYTHONBREAKPOINT']
        self.resources.enter_context(
            swap_attr(sys, 'breakpointhook', sys.__breakpointhook__)) 
Example #7
Source File: test_builtin.py    From android_universal with MIT License 5 votes vote down vote up
def test_breakpoint_with_breakpointhook_set(self):
        my_breakpointhook = MagicMock()
        sys.breakpointhook = my_breakpointhook
        breakpoint()
        my_breakpointhook.assert_called_once_with() 
Example #8
Source File: test_builtin.py    From android_universal with MIT License 5 votes vote down vote up
def test_breakpoint_with_breakpointhook_reset(self):
        my_breakpointhook = MagicMock()
        sys.breakpointhook = my_breakpointhook
        breakpoint()
        my_breakpointhook.assert_called_once_with()
        # Reset the hook and it will not be called again.
        sys.breakpointhook = sys.__breakpointhook__
        with patch('pdb.set_trace') as mock:
            breakpoint()
            mock.assert_called_once_with()
        my_breakpointhook.assert_called_once_with() 
Example #9
Source File: test_builtin.py    From android_universal with MIT License 5 votes vote down vote up
def test_breakpoint_with_args_and_keywords(self):
        my_breakpointhook = MagicMock()
        sys.breakpointhook = my_breakpointhook
        breakpoint(1, 2, 3, four=4, five=5)
        my_breakpointhook.assert_called_once_with(1, 2, 3, four=4, five=5) 
Example #10
Source File: test_builtin.py    From android_universal with MIT License 5 votes vote down vote up
def test_breakpoint_with_passthru_error(self):
        def my_breakpointhook():
            pass
        sys.breakpointhook = my_breakpointhook
        self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5) 
Example #11
Source File: framework.py    From operator with Apache License 2.0 5 votes vote down vote up
def __init__(self, storage, charm_dir, meta, model):

        super().__init__(self, None)

        self.charm_dir = charm_dir
        self.meta = meta
        self.model = model
        self._observers = []      # [(observer_path, method_name, parent_path, event_key)]
        self._observer = weakref.WeakValueDictionary()       # {observer_path: observer}
        self._objects = weakref.WeakValueDictionary()
        self._type_registry = {}  # {(parent_path, kind): cls}
        self._type_known = set()  # {cls}

        if isinstance(storage, (str, pathlib.Path)):
            logger.warning(
                "deprecated: Framework now takes a Storage not a path")
            storage = SQLiteStorage(storage)
        self._storage = storage

        # We can't use the higher-level StoredState because it relies on events.
        self.register_type(StoredStateData, None, StoredStateData.handle_kind)
        stored_handle = Handle(None, StoredStateData.handle_kind, '_stored')
        try:
            self._stored = self.load_snapshot(stored_handle)
        except NoSnapshotError:
            self._stored = StoredStateData(self, '_stored')
            self._stored['event_count'] = 0

        # Hook into builtin breakpoint, so if Python >= 3.7, devs will be able to just do
        # breakpoint(); if Python < 3.7, this doesn't affect anything
        sys.breakpointhook = self.breakpoint

        # Flag to indicate that we already presented the welcome message in a debugger breakpoint
        self._breakpoint_welcomed = False

        # Parse once the env var, which may be used multiple times later
        debug_at = os.environ.get('JUJU_DEBUG_AT')
        self._juju_debug_at = debug_at.split(',') if debug_at else () 
Example #12
Source File: test_framework.py    From operator with Apache License 2.0 5 votes vote down vote up
def test_builtin_breakpoint_hooked(self, fake_stderr):
        # Verify that the proper hook is set.
        with patch.dict(os.environ, {'JUJU_DEBUG_AT': 'all'}):
            self.create_framework()  # creating the framework setups the hook
        with patch('pdb.Pdb.set_trace') as mock:
            # Calling through sys, not breakpoint() directly, so we can run the
            # tests with Py < 3.7.
            sys.breakpointhook()
        self.assertEqual(mock.call_count, 1) 
Example #13
Source File: framework.py    From operator with Apache License 2.0 5 votes vote down vote up
def __init__(self, storage, charm_dir, meta, model):

        super().__init__(self, None)

        self.charm_dir = charm_dir
        self.meta = meta
        self.model = model
        self._observers = []      # [(observer_path, method_name, parent_path, event_key)]
        self._observer = weakref.WeakValueDictionary()       # {observer_path: observer}
        self._objects = weakref.WeakValueDictionary()
        self._type_registry = {}  # {(parent_path, kind): cls}
        self._type_known = set()  # {cls}

        if isinstance(storage, (str, pathlib.Path)):
            logger.warning(
                "deprecated: Framework now takes a Storage not a path")
            storage = SQLiteStorage(storage)
        self._storage = storage

        # We can't use the higher-level StoredState because it relies on events.
        self.register_type(StoredStateData, None, StoredStateData.handle_kind)
        stored_handle = Handle(None, StoredStateData.handle_kind, '_stored')
        try:
            self._stored = self.load_snapshot(stored_handle)
        except NoSnapshotError:
            self._stored = StoredStateData(self, '_stored')
            self._stored['event_count'] = 0

        # Hook into builtin breakpoint, so if Python >= 3.7, devs will be able to just do
        # breakpoint(); if Python < 3.7, this doesn't affect anything
        sys.breakpointhook = self.breakpoint

        # Flag to indicate that we already presented the welcome message in a debugger breakpoint
        self._breakpoint_welcomed = False

        # Parse once the env var, which may be used multiple times later
        debug_at = os.environ.get('JUJU_DEBUG_AT')
        self._juju_debug_at = debug_at.split(',') if debug_at else ()