sys.gettrace

Here are the examples of the python api sys.gettrace taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

68 Examples 7

Example 1

Project: pyqtgraph
Source File: Console.py
View license
    def updateSysTrace(self):
        ## Install or uninstall  sys.settrace handler 
        
        if not self.ui.catchNextExceptionBtn.isChecked() and not self.ui.catchAllExceptionsBtn.isChecked():
            if sys.gettrace() == self.systrace:
                sys.settrace(None)
            return
        
        if self.ui.onlyUncaughtCheck.isChecked():
            if sys.gettrace() == self.systrace:
                sys.settrace(None)
        else:
            if sys.gettrace() is not None and sys.gettrace() != self.systrace:
                self.ui.onlyUncaughtCheck.setChecked(False)
                raise Exception("sys.settrace is in use; cannot monitor for caught exceptions.")
            else:
                sys.settrace(self.systrace)

Example 2

Project: qgisSpaceSyntaxToolkit
Source File: Console.py
View license
    def updateSysTrace(self):
        ## Install or uninstall  sys.settrace handler 
        
        if not self.ui.catchNextExceptionBtn.isChecked() and not self.ui.catchAllExceptionsBtn.isChecked():
            if sys.gettrace() == self.systrace:
                sys.settrace(None)
            return
        
        if self.ui.onlyUncaughtCheck.isChecked():
            if sys.gettrace() == self.systrace:
                sys.settrace(None)
        else:
            if sys.gettrace() is not None and sys.gettrace() != self.systrace:
                self.ui.onlyUncaughtCheck.setChecked(False)
                raise Exception("sys.settrace is in use; cannot monitor for caught exceptions.")
            else:
                sys.settrace(self.systrace)

Example 3

View license
    def test_error_when_set_multiple(self):
        self.monitor._profile.replace(self.bar)
        self.assertIs(sys.gettrace(), self.bar)
        self.monitor._profile.replace(self.bar)
        self.assertIs(sys.gettrace(), self.bar)
        self.monitor._profile.recover()

        self.monitor._profile.replace(self.bar)
        self.assertIs(sys.gettrace(), self.bar)
        with self.assertRaises(RuntimeError):
            self.monitor._profile.replace(None)
            self.assertIs(sys.gettrace(), self.bar)
        self.monitor._profile.recover()
        self.assertIs(sys.gettrace(), self.old)

Example 4

Project: withhacks
Source File: frameutils.py
View license
def _enable_tracing():
    """Enable system-wide tracing, if it wasn't already."""
    global _orig_sys_trace
    try:
        _orig_sys_trace = sys.gettrace()
    except AttributeError:
        _orig_sys_trace = None
    if _orig_sys_trace is None:
        sys.settrace(_dummy_sys_trace)

Example 5

Project: rootpy
Source File: test_roothandler.py
View license
def test_tracing_is_broken():
    def mytrace(*args):
        pass

    orig_trace = sys.gettrace()
    sys.settrace(mytrace)

    try:
        ROOT.Error("rootpy.logger.tests", "Test tracing OK")
    except ROOTError:
        pass
    else:
        assert False, "Should have thrown"

    should_be_mytrace = sys.gettrace()
    sys.settrace(orig_trace)

    assert should_be_mytrace != mytrace, "Tracing is fixed?! Awesome. Now fix the test."

Example 6

Project: dtcov
Source File: dt_tracer.py
View license
    def stop(self):
        """Stop this Tracer."""
        if stopping:
            return
        if hasattr(sys, "gettrace") and self.warn:
            if sys.gettrace() != self._trace:
                msg = "Trace function changed, measurement is likely wrong: %r"
                self.warn(msg % sys.gettrace())
        sys.settrace(None)
        global stopping
        stopping = True

Example 7

Project: TrustRouter
Source File: test_sys.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'fatal error if run with a trace function')
    def test_recursionlimit_recovery(self):
        # NOTE: this test is slightly fragile in that it depends on the current
        # recursion count when executing the test being low enough so as to
        # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
        # macro (see ceval.h).
        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for i in (50, 1000):
                # Issue #5392: stack overflow after hitting recursion limit twice
                sys.setrecursionlimit(i)
                self.assertRaises(RuntimeError, f)
                self.assertRaises(RuntimeError, f)
        finally:
            sys.setrecursionlimit(oldlimit)

Example 8

Project: brython
Source File: test_sys.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'fatal error if run with a trace function')
    def test_recursionlimit_recovery(self):
        # NOTE: this test is slightly fragile in that it depends on the current
        # recursion count when executing the test being low enough so as to
        # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
        # macro (see ceval.h).
        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for i in (50, 1000):
                # Issue #5392: stack overflow after hitting recursion limit twice
                sys.setrecursionlimit(i)
                self.assertRaises(RuntimeError, f)
                self.assertRaises(RuntimeError, f)
        finally:
            sys.setrecursionlimit(oldlimit)

Example 9

Project: brython
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_inst_method_calling(self):
        obj = TracedClass(20)
        self.tracer.runfunc(obj.inst_method_calling, 1)

        expected = {
            self.filemod + ('TracedClass.inst_method_calling',): 1,
            self.filemod + ('TracedClass.inst_method_linear',): 1,
            self.filemod + ('traced_func_linear',): 1,
        }
        self.assertEqual(self.tracer.results().calledfuncs, expected)

Example 10

Project: brython
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_loop_caller_importing(self):
        self.tracer.runfunc(traced_func_importing_caller, 1)

        expected = {
            ((os.path.splitext(trace.__file__)[0] + '.py', 'trace', 'Trace.runfunc'),
                (self.filemod + ('traced_func_importing_caller',))): 1,
            ((self.filemod + ('traced_func_simple_caller',)),
                (self.filemod + ('traced_func_linear',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_simple_caller',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_importing',))): 1,
            ((self.filemod + ('traced_func_importing',)),
                (fix_ext_py(testmod.__file__), 'testmod', 'func')): 1,
        }
        self.assertEqual(self.tracer.results().callers, expected)

Example 11

Project: peek
Source File: tracer.py
View license
    def stop(self):
        """
        Stop this Tracer.
        """
        if hasattr(sys, "gettrace") and self.log:
            if sys.gettrace() != self._trace:
                msg = "Trace function changed, measurement is likely wrong: %r"
                print >> sys.stdout, msg % sys.gettrace()
        sys.settrace(None)

Example 12

View license
    def setUp(self):
        self.old = sys.gettrace()

        def foo():
            pass

        def bar(frame, event, arg):
            pass
        self.foo = foo
        self.bar = bar
        self.monitor = MockNativeMonitor()

Example 13

Project: pikos
Source File: trace_function_manager.py
View license
    def replace(self, function):
        """ Set a new function in sys.settrace.

        If the function has been already set and it is not the same as before
        then RuntimeError is raised.

        """
        if hasattr(self, 'previous'):
            if function != sys.gettrace():
                raise RuntimeError(
                    'Cannot replace profile function more than once')
            return
        else:
            self.previous = sys.gettrace()
        if has_threading:
            threading.settrace(function)
        sys.settrace(function)

Example 14

Project: memory_profiler
Source File: memory_profiler.py
View license
    def enable(self):
        self._original_trace_function = sys.gettrace()
        if self.max_mem is not None:
            sys.settrace(self.trace_max_mem)
        else:
            sys.settrace(self.trace_memory_usage)

Example 15

Project: python-hunter
Source File: tracer.py
View license
    def trace(self, predicate):
        self._handler = predicate
        if self.threading_support:
            self._threading_previous = getattr(threading, '_trace_hook', None)
            threading.settrace(self)
        self._previous = sys.gettrace()
        sys.settrace(self)
        return self

Example 16

Project: karl
Source File: performance.py
View license
    def __enter__(self):
        self.savetrace = prev = sys.gettrace()
        if isinstance(prev, notrace) and isinstance(prev.prev, timetrace):
            self.inner = True
            self.frame_node = prev.prev.frame_node
        else:
            self.frame_node = FrameNode(None, None)
        sys.settrace(self)

Example 17

Project: karl
Source File: performance.py
View license
    def __enter__(self):
        self.savetrace = prev = sys.gettrace()
        if isinstance(prev, notrace) and isinstance(prev.prev, timetrace):
            self.inner = True
            self.frame_node = prev.prev.frame_node
        else:
            self.frame_node = FrameNode(None, None)
        sys.settrace(self)

Example 18

Project: python-mode
Source File: pytest.py
View license
@contextmanager
def replace_trace(trace=None):
    """A context manager that temporary replaces the trace function"""
    oldtrace = sys.gettrace()
    sys.settrace(trace)
    try:
        yield
    finally:
        # specific hack to work around a bug in pycoverage, see
        # https://bitbucket.org/ned/coveragepy/issue/123
        if (oldtrace is not None and not callable(oldtrace) and
            hasattr(oldtrace, 'pytrace')):
            oldtrace = oldtrace.pytrace
        sys.settrace(oldtrace)

Example 19

Project: python-mode
Source File: pytest.py
View license
@contextmanager
def replace_trace(trace=None):
    """A context manager that temporary replaces the trace function"""
    oldtrace = sys.gettrace()
    sys.settrace(trace)
    try:
        yield
    finally:
        # specific hack to work around a bug in pycoverage, see
        # https://bitbucket.org/ned/coveragepy/issue/123
        if (oldtrace is not None and not callable(oldtrace) and
            hasattr(oldtrace, 'pytrace')):
            oldtrace = oldtrace.pytrace
        sys.settrace(oldtrace)

Example 20

Project: profilehooks
Source File: profilehooks.py
View license
        def __call__(self, *args, **kw):
            """Profile a singe call to the function."""
            self.ncalls += 1
            old_trace = sys.gettrace()
            try:
                return self.profiler.runcall(self.fn, args, kw)
            finally: # pragma: nocover
                sys.settrace(old_trace)

Example 21

Project: profilehooks
Source File: profilehooks.py
View license
    def __call__(self, *args, **kw):
        """Profile a singe call to the function."""
        self.ncalls += 1
        if TraceFuncCoverage.tracing: # pragma: nocover
            return self.fn(*args, **kw)
        old_trace = sys.gettrace()
        try:
            TraceFuncCoverage.tracing = True
            return self.tracer.runfunc(self.fn, *args, **kw)
        finally: # pragma: nocover
            sys.settrace(old_trace)
            TraceFuncCoverage.tracing = False

Example 22

Project: iot-utilities
Source File: test_sys.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'fatal error if run with a trace function')
    def test_recursionlimit_recovery(self):
        # NOTE: this test is slightly fragile in that it depends on the current
        # recursion count when executing the test being low enough so as to
        # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
        # macro (see ceval.h).
        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for i in (50, 1000):
                # Issue #5392: stack overflow after hitting recursion limit twice
                sys.setrecursionlimit(i)
                self.assertRaises(RuntimeError, f)
                self.assertRaises(RuntimeError, f)
        finally:
            sys.setrecursionlimit(oldlimit)

Example 23

Project: iot-utilities
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_inst_method_calling(self):
        obj = TracedClass(20)
        self.tracer.runfunc(obj.inst_method_calling, 1)

        expected = {
            self.filemod + ('TracedClass.inst_method_calling',): 1,
            self.filemod + ('TracedClass.inst_method_linear',): 1,
            self.filemod + ('traced_func_linear',): 1,
        }
        self.assertEqual(self.tracer.results().calledfuncs, expected)

Example 24

Project: iot-utilities
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_loop_caller_importing(self):
        self.tracer.runfunc(traced_func_importing_caller, 1)

        expected = {
            ((os.path.splitext(trace.__file__)[0] + '.py', 'trace', 'Trace.runfunc'),
                (self.filemod + ('traced_func_importing_caller',))): 1,
            ((self.filemod + ('traced_func_simple_caller',)),
                (self.filemod + ('traced_func_linear',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_simple_caller',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_importing',))): 1,
            ((self.filemod + ('traced_func_importing',)),
                (fix_ext_py(testmod.__file__), 'testmod', 'func')): 1,
        }
        self.assertEqual(self.tracer.results().callers, expected)

Example 25

Project: iot-utilities
Source File: test_sys.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'fatal error if run with a trace function')
    def test_recursionlimit_recovery(self):
        # NOTE: this test is slightly fragile in that it depends on the current
        # recursion count when executing the test being low enough so as to
        # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
        # macro (see ceval.h).
        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for i in (50, 1000):
                # Issue #5392: stack overflow after hitting recursion limit twice
                sys.setrecursionlimit(i)
                self.assertRaises(RuntimeError, f)
                self.assertRaises(RuntimeError, f)
        finally:
            sys.setrecursionlimit(oldlimit)

Example 26

Project: iot-utilities
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_inst_method_calling(self):
        obj = TracedClass(20)
        self.tracer.runfunc(obj.inst_method_calling, 1)

        expected = {
            self.filemod + ('TracedClass.inst_method_calling',): 1,
            self.filemod + ('TracedClass.inst_method_linear',): 1,
            self.filemod + ('traced_func_linear',): 1,
        }
        self.assertEqual(self.tracer.results().calledfuncs, expected)

Example 27

Project: iot-utilities
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_loop_caller_importing(self):
        self.tracer.runfunc(traced_func_importing_caller, 1)

        expected = {
            ((os.path.splitext(trace.__file__)[0] + '.py', 'trace', 'Trace.runfunc'),
                (self.filemod + ('traced_func_importing_caller',))): 1,
            ((self.filemod + ('traced_func_simple_caller',)),
                (self.filemod + ('traced_func_linear',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_simple_caller',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_importing',))): 1,
            ((self.filemod + ('traced_func_importing',)),
                (fix_ext_py(testmod.__file__), 'testmod', 'func')): 1,
        }
        self.assertEqual(self.tracer.results().callers, expected)

Example 28

Project: iot-utilities
Source File: test_sys.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'fatal error if run with a trace function')
    def test_recursionlimit_recovery(self):
        # NOTE: this test is slightly fragile in that it depends on the current
        # recursion count when executing the test being low enough so as to
        # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
        # macro (see ceval.h).
        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for i in (50, 1000):
                # Issue #5392: stack overflow after hitting recursion limit twice
                sys.setrecursionlimit(i)
                self.assertRaises(RuntimeError, f)
                self.assertRaises(RuntimeError, f)
        finally:
            sys.setrecursionlimit(oldlimit)

Example 29

Project: iot-utilities
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_inst_method_calling(self):
        obj = TracedClass(20)
        self.tracer.runfunc(obj.inst_method_calling, 1)

        expected = {
            self.filemod + ('TracedClass.inst_method_calling',): 1,
            self.filemod + ('TracedClass.inst_method_linear',): 1,
            self.filemod + ('traced_func_linear',): 1,
        }
        self.assertEqual(self.tracer.results().calledfuncs, expected)

Example 30

Project: iot-utilities
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_loop_caller_importing(self):
        self.tracer.runfunc(traced_func_importing_caller, 1)

        expected = {
            ((os.path.splitext(trace.__file__)[0] + '.py', 'trace', 'Trace.runfunc'),
                (self.filemod + ('traced_func_importing_caller',))): 1,
            ((self.filemod + ('traced_func_simple_caller',)),
                (self.filemod + ('traced_func_linear',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_simple_caller',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_importing',))): 1,
            ((self.filemod + ('traced_func_importing',)),
                (fix_ext_py(testmod.__file__), 'testmod', 'func')): 1,
        }
        self.assertEqual(self.tracer.results().callers, expected)

Example 31

Project: iot-utilities
Source File: test_sys.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'fatal error if run with a trace function')
    def test_recursionlimit_recovery(self):
        # NOTE: this test is slightly fragile in that it depends on the current
        # recursion count when executing the test being low enough so as to
        # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
        # macro (see ceval.h).
        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for i in (50, 1000):
                # Issue #5392: stack overflow after hitting recursion limit twice
                sys.setrecursionlimit(i)
                self.assertRaises(RuntimeError, f)
                self.assertRaises(RuntimeError, f)
        finally:
            sys.setrecursionlimit(oldlimit)

Example 32

Project: iot-utilities
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_inst_method_calling(self):
        obj = TracedClass(20)
        self.tracer.runfunc(obj.inst_method_calling, 1)

        expected = {
            self.filemod + ('TracedClass.inst_method_calling',): 1,
            self.filemod + ('TracedClass.inst_method_linear',): 1,
            self.filemod + ('traced_func_linear',): 1,
        }
        self.assertEqual(self.tracer.results().calledfuncs, expected)

Example 33

Project: iot-utilities
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_loop_caller_importing(self):
        self.tracer.runfunc(traced_func_importing_caller, 1)

        expected = {
            ((os.path.splitext(trace.__file__)[0] + '.py', 'trace', 'Trace.runfunc'),
                (self.filemod + ('traced_func_importing_caller',))): 1,
            ((self.filemod + ('traced_func_simple_caller',)),
                (self.filemod + ('traced_func_linear',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_simple_caller',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_importing',))): 1,
            ((self.filemod + ('traced_func_importing',)),
                (fix_ext_py(testmod.__file__), 'testmod', 'func')): 1,
        }
        self.assertEqual(self.tracer.results().callers, expected)

Example 34

Project: coveragepy
Source File: pytracer.py
View license
    def stop(self):
        """Stop this Tracer."""
        self.stopped = True
        if self.threading and self.thread.ident != self.threading.currentThread().ident:
            # Called on a different thread than started us: we can't unhook
            # ourselves, but we've set the flag that we should stop, so we
            # won't do any more tracing.
            return

        if self.warn:
            if sys.gettrace() != self._trace:
                msg = "Trace function changed, measurement is likely wrong: %r"
                self.warn(msg % (sys.gettrace(),))

        sys.settrace(None)

Example 35

Project: coveragepy
Source File: pytracer.py
View license
    def stop(self):
        """Stop this Tracer."""
        self.stopped = True
        if self.threading and self.thread.ident != self.threading.currentThread().ident:
            # Called on a different thread than started us: we can't unhook
            # ourselves, but we've set the flag that we should stop, so we
            # won't do any more tracing.
            return

        if self.warn:
            if sys.gettrace() != self._trace:
                msg = "Trace function changed, measurement is likely wrong: %r"
                self.warn(msg % (sys.gettrace(),))

        sys.settrace(None)

Example 36

View license
    def test_tracerInstalled(self):
        """
        L{trial.Options} handles C{"--coverage"} by installing a trace
        hook to record coverage information.
        """
        options = trial.Options()
        options.parseOptions(["--coverage"])
        self.assertEqual(sys.gettrace(), options.tracer.globaltrace)

Example 37

View license
    def test_tracerInstalled(self):
        """
        L{trial.Options} handles C{"--coverage"} by installing a trace
        hook to record coverage information.
        """
        options = trial.Options()
        options.parseOptions(["--coverage"])
        self.assertEqual(sys.gettrace(), options.tracer.globaltrace)

Example 38

Project: vprof
Source File: memory_profile.py
View license
    def __init__(self):
        self._all_code = set()
        self._events_list = deque()
        self._original_trace_function = sys.gettrace()
        self._pid = os.getpid()
        self._resulting_events = []
        self.mem_overhead = None

Example 39

Project: rootpy
Source File: magic.py
View license
def re_execute_with_exception(frame, exception, traceback):
    """
    Dark magic. Causes ``frame`` to raise an exception at the current location
    with ``traceback`` appended to it.

    Note that since the line tracer is raising an exception, the interpreter
    disables the global trace, so it's not possible to restore the previous
    tracing conditions.
    """
    if sys.gettrace() == globaltrace:
        # If our trace handler is already installed, that means that this
        # function has been called twice before the line tracer had a chance to
        # run. That can happen if more than one exception was logged.
        return

    call_lineno = frame.f_lineno

    def intercept_next_line(f, why, *args):
        if f is not frame:
            return
        set_linetrace_on_frame(f)
        # Undo modifications to the callers code (ick ick ick)
        back_like_nothing_happened()
        # Raise exception in (almost) the perfect place (except for duplication)
        if sys.version_info[0] < 3:
            #raise exception.__class__, exception, traceback
            raise exception
        raise exception.with_traceback(traceback)

    set_linetrace_on_frame(frame, intercept_next_line)

    linestarts = list(dis.findlinestarts(frame.f_code))
    linestarts = [a for a, l in linestarts if l >= call_lineno]

    # Jump target
    dest = linestarts[0]

    oc = frame.f_code.co_code[frame.f_lasti]
    if sys.version_info[0] < 3:
        oc = ord(oc)
    opcode_size = 2 if oc >= opcode.HAVE_ARGUMENT else 0
    # Opcode to overwrite
    where = frame.f_lasti + 1 + opcode_size

    #dis.disco(frame.f_code)
    pc = PyCodeObject.from_address(id(frame.f_code))
    back_like_nothing_happened = pc.co_code.contents.inject_jump(where, dest)
    #print("#"*100)
    #dis.disco(frame.f_code)

    sys.settrace(globaltrace)

Example 40

Project: iktomi
Source File: functools.py
View license
    def test_return_locals_debugger_events(self):
        '''Insure debugging function gets events for function decorated with
        return_locals at least the same as for function itself.'''
        def collect_events(func):
            events = []
            def tracer(frame, event, args):
                events.append((frame.f_code, event))
                return tracer
            old_tracer = sys.gettrace()
            sys.settrace(tracer)
            try:
                func()
            finally:
                sys.settrace(old_tracer)
            return events
        def inner():
            return 2
        def outer():
            a = 1
            b = inner()
        events1 = set(collect_events(outer))
        events2 = set(collect_events(return_locals(outer)))
        self.assertTrue(events2.issuperset(events1))

Example 41

Project: brython
Source File: test_sys_settrace.py
View license
    def test_exception_arguments(self):
        def f():
            x = 0
            # this should raise an error
            x.no_such_attr
        def g(frame, event, arg):
            if (event == 'exception'):
                type, exception, trace = arg
                self.assertIsInstance(exception, Exception)
            return g

        existing = sys.gettrace()
        try:
            sys.settrace(g)
            try:
                f()
            except AttributeError:
                # this is expected
                pass
        finally:
            sys.settrace(existing)

Example 42

View license
    def test_error_when_unset(self):
        with self.assertRaises(RuntimeError):
            self.monitor._profile.recover()
        self.assertIs(sys.gettrace(), self.old)

Example 43

Project: feat
Source File: time.py
View license
def _debugger_scale():
    if sys.gettrace() is None:
        return 1
    else:
        return 4

Example 44

Project: feat
Source File: common.py
View license
    def assert_not_skipped(self):
        if self.skip_coverage and sys.gettrace():
            raise unittest.SkipTest("Test Skipped during coverage")

Example 45

Project: feat
Source File: common.py
View license
    def assert_not_skipped(self):
        if self.skip_coverage and sys.gettrace():
            raise SkipTest("Test Skipped during coverage")

Example 46

Project: feat
Source File: common.py
View license
    def assert_not_skipped(self):
        if self.skip_coverage and sys.gettrace():
            raise SkipTest("Test Skipped during coverage")

Example 47

Project: feat
Source File: common.py
View license
    def assert_not_skipped(self):
        if self.skip_coverage and sys.gettrace():
            raise SkipTest("Test Skipped during coverage")

Example 48

Project: datafari
Source File: test_threading.py
View license
    @cpython_only
    @unittest.skipIf(_testcapi is None, "need _testcapi module")
    def test_frame_tstate_tracing(self):
        # Issue #14432: Crash when a generator is created in a C thread that is
        # destroyed while the generator is still used. The issue was that a
        # generator contains a frame, and the frame kept a reference to the
        # Python state of the destroyed C thread. The crash occurs when a trace
        # function is setup.

        def noop_trace(frame, event, arg):
            # no operation
            return noop_trace

        def generator():
            while 1:
                yield "genereator"

        def callback():
            if callback.gen is None:
                callback.gen = generator()
            return next(callback.gen)
        callback.gen = None

        old_trace = sys.gettrace()
        sys.settrace(noop_trace)
        try:
            # Install a trace function
            threading.settrace(noop_trace)

            # Create a generator in a C thread which exits after the call
            _testcapi.call_in_temporary_c_thread(callback)

            # Call the generator in a different Python thread, check that the
            # generator didn't keep a reference to the destroyed thread state
            for test in range(3):
                # The trace function is still called here
                callback()
        finally:
            sys.settrace(old_trace)

Example 49

Project: python-csp
Source File: os_process.py
View license
    def run(self): #, event=None):
        """Called automatically when the L{start} methods is called.
        """
        try:
            generator = self._target(*self._args, **self._kwargs)
            while sys.gettrace() is None:
                next(generator)
            else:
                # If the tracer is running execute the target only once.
                next(generator)
                logging.info('Server process detected a tracer running.')
                # Be explicit.
                return None
        except ChannelPoison:
            _debug('{0}s in {1} got ChannelPoison exception'.format(str(self), self.getPid()))
            self.referent_visitor(self._args + tuple(self._kwargs.values()))
#            if self._popen is not None: self.terminate()
        except KeyboardInterrupt:
            sys.exit()
        except Exception:
            typ, excn, tback = sys.exc_info()
            sys.excepthook(typ, excn, tback)

Example 50

Project: python-csp
Source File: os_thread.py
View license
    def run(self): #, event=None):
        """Called automatically when the L{start} methods is called.
        """
        try:
            generator = self._Thread__target(*self._Thread__args, **self._Thread__kwargs)
            while sys.gettrace() is None:
                next(generator)
            else:
                # If the tracer is running execute the target only once.
                next(generator)
                logging.info('Server process detected a tracer running.')
                # Be explicit.
                return None
        except ChannelPoison:
            _debug('{0} in {1} got ChannelPoison exception'.format(str(self), self.getPid()))
            self.referent_visitor(self._Thread__args + tuple(self._Thread__kwargs.values()))
#            if self._popen is not None: self.terminate()
        except KeyboardInterrupt:
            sys.exit()
        except Exception:
            typ, excn, tback = sys.exc_info()
            sys.excepthook(typ, excn, tback)