Python sys.gettrace() Examples

The following are 30 code examples of sys.gettrace(). 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: tracer.py    From qdb with Apache License 2.0 6 votes vote down vote up
def disable(self, mode='soft'):
        """
        Stops tracing.
        """
        try:
            if mode == 'soft':
                self.clear_all_breaks()
                self.set_continue()
                # Remove this instance so that new ones may be created.
                self.__class__._instance = None
            elif mode == 'hard':
                sys.exit(1)
            else:
                raise ValueError("mode must be 'hard' or 'soft'")
        finally:
            self.restore_output_streams()
            if self.log_handler:
                self.log_handler.pop_application()
            self.cmd_manager.stop()
            if sys.gettrace() is self.trace_dispatch:
                sys.settrace(None) 
Example #2
Source File: test_sys.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_recursionlimit_recovery(self):
        if hasattr(sys, 'gettrace') and sys.gettrace():
            self.skipTest('fatal error if run with a trace function')

        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for depth in (10, 25, 50, 75, 100, 250, 1000):
                try:
                    sys.setrecursionlimit(depth)
                except RecursionError:
                    # Issue #25274: The recursion limit is too low at the
                    # current recursion depth
                    continue

                # Issue #5392: test stack overflow after hitting recursion
                # limit twice
                self.assertRaises(RecursionError, f)
                self.assertRaises(RecursionError, f)
        finally:
            sys.setrecursionlimit(oldlimit) 
Example #3
Source File: pytest_timeout.py    From pytest-timeout with MIT License 6 votes vote down vote up
def is_debugging():
    """Detect if a debugging session is in progress.

    This looks at both pytest's builtin pdb support as well as
    externally installed debuggers using some heuristics.

     This is done by checking if either of the following conditions is
     true:

     1. Examines the trace function to see if the module it originates
        from is in KNOWN_DEBUGGING_MODULES.
     2. Check is SUPPRESS_TIMEOUT is set to True.
    """
    global SUPPRESS_TIMEOUT, KNOWN_DEBUGGING_MODULES
    if SUPPRESS_TIMEOUT:
        return True
    trace_func = sys.gettrace()
    if trace_func and inspect.getmodule(trace_func):
        for name in KNOWN_DEBUGGING_MODULES:
            if name in inspect.getmodule(trace_func):
                return True
    return False 
Example #4
Source File: test_scope.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def testInteractionWithTraceFunc(self):

        import sys
        def tracer(a,b,c):
            return tracer

        def adaptgetter(name, klass, getter):
            kind, des = getter
            if kind == 1:       # AV happens when stepping from this line to next
                if des == "":
                    des = "_%s__%s" % (klass.__name__, name)
                return lambda obj: getattr(obj, des)

        class TestClass:
            pass

        self.addCleanup(sys.settrace, sys.gettrace())
        sys.settrace(tracer)
        adaptgetter("foo", TestClass, (1, ""))
        sys.settrace(None)

        self.assertRaises(TypeError, sys.settrace) 
Example #5
Source File: pickletester.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def no_tracing(func):
    """Decorator to temporarily turn off tracing for the duration of a test."""
    if not hasattr(sys, 'gettrace'):
        return func
    else:
        def wrapper(*args, **kwargs):
            original_trace = sys.gettrace()
            try:
                sys.settrace(None)
                return func(*args, **kwargs)
            finally:
                sys.settrace(original_trace)
        wrapper.__name__ = func.__name__
        return wrapper


# Return True if opcode code appears in the pickle, else False. 
Example #6
Source File: conftest.py    From pdbpp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def restore_settrace(monkeypatch):
    """(Re)store sys.gettrace after test run.

    This is required to re-enable coverage tracking.
    """
    assert sys.gettrace() is _orig_trace

    orig_settrace = sys.settrace

    # Wrap sys.settrace to restore original tracing function (coverage)
    # with `sys.settrace(None)`.
    def settrace(func):
        if func is None:
            orig_settrace(_orig_trace)
        else:
            orig_settrace(func)
    monkeypatch.setattr("sys.settrace", settrace)

    yield

    newtrace = sys.gettrace()
    if newtrace is not _orig_trace:
        sys.settrace(_orig_trace)
        assert newtrace is None 
Example #7
Source File: test_scope.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def testInteractionWithTraceFunc(self):

        import sys
        def tracer(a,b,c):
            return tracer

        def adaptgetter(name, klass, getter):
            kind, des = getter
            if kind == 1:       # AV happens when stepping from this line to next
                if des == "":
                    des = "_%s__%s" % (klass.__name__, name)
                return lambda obj: getattr(obj, des)

        class TestClass:
            pass

        self.addCleanup(sys.settrace, sys.gettrace())
        sys.settrace(tracer)
        adaptgetter("foo", TestClass, (1, ""))
        sys.settrace(None)

        self.assertRaises(TypeError, sys.settrace) 
Example #8
Source File: workflow.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def run_with_trace(config, script, **kwargs):
    """Same as run, but use the trace-inputlocator functionality to capture InputLocator calls"""
    from cea.tests.trace_inputlocator import create_trace_function, update_trace_data, meta_to_yaml

    if "multiprocessing" in kwargs:
        # we can only trace single processes
        kwargs["multiprocessing"] = False

    # stuff needed for trace-inputlocator
    script_start = datetime.datetime.now()
    results_set = set()
    orig_trace = sys.gettrace()
    sys.settrace(create_trace_function(results_set))

    run(config, script, **kwargs)  # <------------------------------ this is where we run the script!

    sys.settrace(orig_trace)

    # update the trace data
    trace_data = set()
    update_trace_data(config, cea.inputlocator.InputLocator(config.scenario), results_set, script,
                      script_start, trace_data)
    meta_to_yaml(config, trace_data, config.trace_inputlocator.meta_output_file) 
Example #9
Source File: Console.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: trace_inputlocator.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def main(config):
    # force single-threaded execution, see settrace docs for why
    config.multiprocessing = False
    locator = cea.inputlocator.InputLocator(config.scenario)

    trace_data = set()  # set used for graphviz output -> {(direction, script, locator_method, path, file)}

    for script_name in config.trace_inputlocator.scripts:
        script_func = getattr(cea.api, script_name.replace('-', '_'))
        script_start = datetime.now()
        results_set = set()  # {(locator_method, filename)}

        orig_trace = sys.gettrace()
        sys.settrace(create_trace_function(results_set))
        script_func(config)  # <------------------------------ this is where we run the script!
        sys.settrace(orig_trace)

        update_trace_data(config, locator, results_set, script_name,
                          script_start, trace_data)
    print(trace_data)
    scripts = sorted(set([td[1] for td in trace_data]))
    config.restricted_to = None

    meta_to_yaml(config, trace_data, config.trace_inputlocator.meta_output_file)
    print('Trace Complete') 
Example #11
Source File: test_sys.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_recursionlimit_recovery(self):
        if hasattr(sys, 'gettrace') and sys.gettrace():
            self.skipTest('fatal error if run with a trace function')

        # 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 #12
Source File: test_sys_settrace.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.using_gc = gc.isenabled()
        gc.disable()
        self.addCleanup(sys.settrace, sys.gettrace()) 
Example #13
Source File: test_threading.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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 #14
Source File: test_sys_settrace.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.addCleanup(sys.settrace, sys.gettrace()) 
Example #15
Source File: test_sys_settrace.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.using_gc = gc.isenabled()
        gc.disable()
        self.addCleanup(sys.settrace, sys.gettrace()) 
Example #16
Source File: test_sys_settrace.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_set_and_retrieve_none(self):
        sys.settrace(None)
        assert sys.gettrace() is None 
Example #17
Source File: test_scope.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def testLocalsClass_WithTrace(self):
        # Issue23728: after the trace function returns, the locals()
        # dictionary is used to update all variables, this used to
        # include free variables. But in class statements, free
        # variables are not inserted...
        import sys
        self.addCleanup(sys.settrace, sys.gettrace())
        sys.settrace(lambda a,b,c:None)
        x = 12

        class C:
            def f(self):
                return x

        self.assertEqual(x, 12) # Used to raise UnboundLocalError 
Example #18
Source File: support.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def no_tracing(func):
    """Decorator to temporarily turn off tracing for the duration of a test."""
    if not hasattr(sys, 'gettrace'):
        return func
    else:
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            original_trace = sys.gettrace()
            try:
                sys.settrace(None)
                return func(*args, **kwargs)
            finally:
                sys.settrace(original_trace)
        return wrapper 
Example #19
Source File: test_sys_settrace.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.addCleanup(sys.settrace, sys.gettrace())
        sys.settrace(None) 
Example #20
Source File: test_sys_settrace.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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)


# 'Jump' tests: assigning to frame.f_lineno within a trace function
# moves the execution position - it's how debuggers implement a Jump
# command (aka. "Set next statement"). 
Example #21
Source File: test_sys_settrace.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.addCleanup(sys.settrace, sys.gettrace()) 
Example #22
Source File: test_sys_settrace.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_set_and_retrieve_none(self):
        sys.settrace(None)
        assert sys.gettrace() is None 
Example #23
Source File: regrtest.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def get_sys_gettrace(self):
        return sys.gettrace() 
Example #24
Source File: tracing.py    From stackprinter with MIT License 5 votes vote down vote up
def enable(self, force=False, current_depth=None):
        if current_depth is None:
            current_depth = count_stack(sys._getframe(1))
        self.starting_depth = current_depth
        self.previous_frame = None
        self.trace_before = sys.gettrace()
        if (self.trace_before is not None) and not force:
            raise Exception("There is already a trace function registered: %r" % self.trace_before)
        sys.settrace(self.trace) 
Example #25
Source File: test_scope.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def testLocalsClass_WithTrace(self):
        # Issue23728: after the trace function returns, the locals()
        # dictionary is used to update all variables, this used to
        # include free variables. But in class statements, free
        # variables are not inserted...
        import sys
        self.addCleanup(sys.settrace, sys.gettrace())
        sys.settrace(lambda a,b,c:None)
        x = 12

        class C:
            def f(self):
                return x

        self.assertEqual(x, 12) # Used to raise UnboundLocalError 
Example #26
Source File: test_threading.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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 #27
Source File: test_trace.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.addCleanup(sys.settrace, sys.gettrace())
        self.tracer = Trace(count=0, trace=0, countcallers=1)
        self.filemod = my_file_and_modname() 
Example #28
Source File: test_trace.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.addCleanup(sys.settrace, sys.gettrace())
        self.tracer = Trace(count=0, trace=0, countfuncs=1)
        self.filemod = my_file_and_modname()
        self._saved_tracefunc = sys.gettrace() 
Example #29
Source File: test_trace.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.my_py_filename = fix_ext_py(__file__)
        self.addCleanup(sys.settrace, sys.gettrace()) 
Example #30
Source File: test_trace.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.addCleanup(sys.settrace, sys.gettrace())
        self.tracer = Trace(count=1, trace=0, countfuncs=0, countcallers=0)
        self.my_py_filename = fix_ext_py(__file__)