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.

38 Examples 7

Example 1

Project: pyqtgraph Source File: Console.py
    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: pikos Source File: test_trace_function_manager.py
Function: test_error_when_set_multiple
    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 3

Project: withhacks Source File: frameutils.py
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 4

Project: rootpy Source File: test_roothandler.py
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 5

Project: dtcov Source File: dt_tracer.py
Function: stop
    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 6

Project: TrustRouter Source File: test_sys.py
    @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 7

Project: brython Source File: test_trace.py
    @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 8

Project: brython Source File: test_trace.py
    @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 9

Project: peek Source File: tracer.py
Function: stop
    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 10

Project: pikos Source File: test_trace_function_manager.py
Function: set_up
    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 11

Project: pikos Source File: trace_function_manager.py
    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 12

Project: memory_profiler Source File: memory_profiler.py
Function: enable
    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 13

Project: python-hunter Source File: tracer.py
    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 14

Project: karl Source File: performance.py
Function: enter
    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 15

Project: python-mode Source File: pytest.py
@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 16

Project: profilehooks Source File: profilehooks.py
Function: call
        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 17

Project: profilehooks Source File: profilehooks.py
Function: call
    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 18

Project: coveragepy Source File: pytracer.py
Function: stop
    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 19

Project: SubliminalCollaborator Source File: test_script.py
    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 20

Project: vprof Source File: memory_profile.py
Function: init
    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 21

Project: rootpy Source File: magic.py
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 22

Project: iktomi Source File: functools.py
    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 23

Project: brython Source File: test_sys_settrace.py
    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 24

Project: pikos Source File: test_trace_function_manager.py
    def test_error_when_unset(self):
        with self.assertRaises(RuntimeError):
            self.monitor._profile.recover()
        self.assertIs(sys.gettrace(), self.old)

Example 25

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

Example 26

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

Example 27

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

Example 28

Project: datafari Source File: test_threading.py
Function: test_frame_tstate_tracing
    @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 29

Project: python-csp Source File: os_process.py
Function: run
    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 30

Project: python-csp Source File: os_thread.py
Function: run
    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)

Example 31

Project: pytest-benchmark Source File: fixture.py
    def _make_runner(self, function_to_benchmark, args, kwargs):
        def runner(loops_range, timer=self._timer):
            gc_enabled = gc.isenabled()
            if self._disable_gc:
                gc.disable()
            tracer = sys.gettrace()
            sys.settrace(None)
            try:
                if loops_range:
                    start = timer()
                    for _ in loops_range:
                        function_to_benchmark(*args, **kwargs)
                    end = timer()
                    return end - start
                else:
                    start = timer()
                    result = function_to_benchmark(*args, **kwargs)
                    end = timer()
                    return end - start, result
            finally:
                sys.settrace(tracer)
                if gc_enabled:
                    gc.enable()

        return runner

Example 32

Project: memprof Source File: memprof.py
Function: call
    def __call__(self, *args, **kwargs):
        print("memprof starting (min. size: %d)" % (self.threshold))

        if self.__start == -1:
            self.__prev = self.__start = time.time()
            self.__log = open(self.__logfile, "w")
        else:
            self.__log = open(self.__logfile, "a")

            self.__checkTimes.append(self.__prev - self.__start + 0.00000001)
            self.__log.write("%f\n" % (self.__prev - self.__start + 0.00000001))

            self.__checkTimes.append(time.time() - self.__start)
            self.__log.write("%f\n" % (time.time() - self.__start))

            self.__log.write("RESTART\n")

            for key in self.__cache.keys():
                self.__cache[key].append(0)
                self.__cache[key].append(0)

        curr_tracer = sys.gettrace()
        sys.settrace(self.tracer)

        res = self.func(*args, **kwargs)

        sys.settrace(curr_tracer)

        self.__log.close()
        self.__ticks = 0

        if self.__plot:
            gen_plot(self.__logfile, self.threshold)

        print("memprof done")

        return res

Example 33

Project: karl Source File: performance.py
Function: enter
    def __enter__(self):
        self.prev = sys.gettrace()
        sys.settrace(self)

Example 34

Project: iot-utilities Source File: test_threading.py
Function: test_frame_tstate_tracing
    @cpython_only
    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 "generator"

        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
            import _testcapi
            _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 35

Project: coveragepy Source File: collector.py
Function: start
    def start(self):
        """Start collecting trace information."""
        if self._collectors:
            self._collectors[-1].pause()

        # Check to see whether we had a fullcoverage tracer installed. If so,
        # get the stack frames it stashed away for us.
        traces0 = []
        fn0 = sys.gettrace()
        if fn0:
            tracer0 = getattr(fn0, '__self__', None)
            if tracer0:
                traces0 = getattr(tracer0, 'traces', [])

        try:
            # Install the tracer on this thread.
            fn = self._start_tracer()
        except:
            if self._collectors:
                self._collectors[-1].resume()
            raise

        # If _start_tracer succeeded, then we add ourselves to the global
        # stack of collectors.
        self._collectors.append(self)

        # Replay all the events from fullcoverage into the new trace function.
        for args in traces0:
            (frame, event, arg), lineno = args
            try:
                fn(frame, event, arg, lineno=lineno)
            except TypeError:
                raise Exception("fullcoverage must be run with the C trace function.")

        # Install our installation tracer in threading, to jump start other
        # threads.
        if self.threading:
            self.threading.settrace(self._installation_trace)

Example 36

Project: vprof Source File: code_heatmap.py
Function: init
    def __init__(self):
        self._all_code = set()
        self._original_trace_function = sys.gettrace()
        self.heatmap = defaultdict(lambda: defaultdict(int))

Example 37

Project: vprof Source File: code_heatmap_test.py
Function: test_init
    def testInit(self):
        self._calc.__init__()
        self.assertEqual(self._calc._all_code, set())
        self.assertEqual(self._calc._original_trace_function, sys.gettrace())
        self.assertEqual(self._calc.heatmap, defaultdict(int))

Example 38

Project: great-justice Source File: __init__.py
Function: enter
    def __enter__(self):
        self._old_trace = sys.gettrace()
        sys.settrace(self.log_call)