Python sys.settrace() Examples

The following are 30 code examples for showing how to use sys.settrace(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module sys , or try the search function .

Example 1
Project: codimension   Author: SergeySatskiy   File: base_cdm_dbg.py    License: GNU General Public License v3.0 6 votes vote down vote up
def set_trace(self, frame=None):
        """Starts debugging from 'frame'"""
        if frame is None:
            frame = sys._getframe().f_back  # Skip set_trace method

        if sys.version_info[0] == 2:
            stopOnHandleLine = self._dbgClient.handleLine.func_code
        else:
            stopOnHandleLine = self._dbgClient.handleLine.__code__

        frame.f_trace = self.trace_dispatch
        while frame.f_back is not None:
            # stop at erics debugger frame or a threading bootstrap
            if frame.f_back.f_code == stopOnHandleLine:
                frame.f_trace = self.trace_dispatch
                break

            frame = frame.f_back

        self.stop_everywhere = True
        sys.settrace(self.trace_dispatch)
        sys.setprofile(self._dbgClient.callTraceEnabled) 
Example 2
Project: tf-pose   Author: SrikanthVelpuri   File: Console.py    License: 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 3
Project: pdbpp   Author: pdbpp   File: conftest.py    License: 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 4
Project: meddle   Author: glmcdona   File: bdb.py    License: MIT License 6 votes vote down vote up
def run(self, cmd, globals=None, locals=None):
        if globals is None:
            import __main__
            globals = __main__.__dict__
        if locals is None:
            locals = globals
        self.reset()
        sys.settrace(self.trace_dispatch)
        if not isinstance(cmd, types.CodeType):
            cmd = cmd+'\n'
        try:
            exec cmd in globals, locals
        except BdbQuit:
            pass
        finally:
            self.quitting = 1
            sys.settrace(None) 
Example 5
Project: ironpython2   Author: IronLanguages   File: adb.py    License: Apache License 2.0 6 votes vote down vote up
def dispatch_call(self, frame, arg):
        traceenter("dispatch_call",_dumpf(frame))
        frame.f_locals['__axstack_address__'] = axdebug.GetStackAddress()
        if frame is self.botframe:
            trace("dispatch_call is self.botframe - returning tracer")
            return self.trace_dispatch
        # Not our bottom frame.  If we have a document for it,
        # then trace it, otherwise run at full speed.
        if self.codeContainerProvider.FromFileName(frame.f_code.co_filename) is None:
            trace("dispatch_call has no document for", _dumpf(frame), "- skipping trace!")
##                      sys.settrace(None)
            return None
        return self.trace_dispatch

#               rc =  bdb.Bdb.dispatch_call(self, frame, arg)
#               trace("dispatch_call", _dumpf(frame),"returned",rc)
#               return rc 
Example 6
Project: ironpython2   Author: IronLanguages   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def post_mortem(t=None):
	if t is None:
		t = sys.exc_info()[2] # Will be valid if we are called from an except handler.
	if t is None:
		try:
			t = sys.last_traceback
		except AttributeError:
			print "No traceback can be found from which to perform post-mortem debugging!"
			print "No debugging can continue"
			return
	p = _GetCurrentDebugger()
	if p.frameShutdown: return # App closing
	# No idea why I need to settrace to None - it should have been reset by now?
	sys.settrace(None)
	p.reset()
	while t.tb_next != None: t = t.tb_next
	p.bAtPostMortem = 1
	p.prep_run(None)
	try:
		p.interaction(t.tb_frame, t)
	finally:
		t = None
		p.bAtPostMortem = 0
		p.done_run() 
Example 7
Project: ironpython2   Author: IronLanguages   File: debugger.py    License: Apache License 2.0 6 votes vote down vote up
def set_trace(self):
		# Start debugging from _2_ levels up!
		try:
			1 + ''
		except:
			frame = sys.exc_info()[2].tb_frame.f_back.f_back
		self.reset()
		self.userbotframe = None
		while frame:
			# scriptutils.py creates a local variable with name
			# '_debugger_stop_frame_', and we dont go past it
			# (everything above this is Pythonwin framework code)
			if "_debugger_stop_frame_" in frame.f_locals:
				self.userbotframe = frame
				break

			frame.f_trace = self.trace_dispatch
			self.botframe = frame
			frame = frame.f_back
		self.set_step()
		sys.settrace(self.trace_dispatch) 
Example 8
Project: ironpython2   Author: IronLanguages   File: test_scope.py    License: Apache License 2.0 6 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
        sys.settrace(lambda a,b,c:None)
        try:
            x = 12

            class C:
                def f(self):
                    return x

            self.assertEqual(x, 12) # Used to raise UnboundLocalError
        finally:
            sys.settrace(None) 
Example 9
Project: ironpython2   Author: IronLanguages   File: test_scope.py    License: 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

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

        self.assertRaises(TypeError, sys.settrace) 
Example 10
Project: ironpython2   Author: IronLanguages   File: test_sys_settrace.py    License: Apache License 2.0 6 votes vote down vote up
def run_test_for_event(self, event):
        """Tests that an exception raised in response to the given event is
        handled OK."""
        self.raiseOnEvent = event
        try:
            for i in xrange(sys.getrecursionlimit() + 1):
                sys.settrace(self.trace)
                try:
                    self.f()
                except ValueError:
                    pass
                else:
                    self.fail("exception not raised!")
        except RuntimeError:
            self.fail("recursion counter not reset")

    # Test the handling of exceptions raised by each kind of trace event. 
Example 11
Project: ironpython2   Author: IronLanguages   File: test_sys_settrace.py    License: Apache License 2.0 6 votes vote down vote up
def test_trash_stack(self):
        def f():
            for i in range(5):
                print i  # line tracing will raise an exception at this line

        def g(frame, why, extra):
            if (why == 'line' and
                frame.f_lineno == f.func_code.co_firstlineno + 2):
                raise RuntimeError, "i am crashing"
            return g

        sys.settrace(g)
        try:
            f()
        except RuntimeError:
            # the test is really that this doesn't segfault:
            import gc
            gc.collect()
        else:
            self.fail("exception not propagated")


# '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 12
Project: ironpython2   Author: IronLanguages   File: test_sys_settrace.py    License: Apache License 2.0 6 votes vote down vote up
def test_jump_to_firstlineno(self):
        # This tests that PDB can jump back to the first line in a
        # file.  See issue #1689458.  It can only be triggered in a
        # function call if the function is defined on a single line.
        code = compile("""
# Comments don't count.
output.append(2)  # firstlineno is here.
output.append(3)
output.append(4)
""", "<fake module>", "exec")
        class fake_function:
            func_code = code
        tracer = JumpTracer(fake_function, 2, 0)
        sys.settrace(tracer.trace)
        namespace = {"output": []}
        exec code in namespace
        sys.settrace(None)
        self.compare_jump_output([2, 3, 2, 3, 4], namespace["output"]) 
Example 13
Project: ironpython2   Author: IronLanguages   File: pickletester.py    License: 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 14
Project: ironpython2   Author: IronLanguages   File: bdb.py    License: Apache License 2.0 6 votes vote down vote up
def run(self, cmd, globals=None, locals=None):
        if globals is None:
            import __main__
            globals = __main__.__dict__
        if locals is None:
            locals = globals
        self.reset()
        sys.settrace(self.trace_dispatch)
        if not isinstance(cmd, types.CodeType):
            cmd = cmd+'\n'
        try:
            exec cmd in globals, locals
        except BdbQuit:
            pass
        finally:
            self.quitting = 1
            sys.settrace(None) 
Example 15
Project: ironpython2   Author: IronLanguages   File: bdb.py    License: Apache License 2.0 6 votes vote down vote up
def runeval(self, expr, globals=None, locals=None):
        if globals is None:
            import __main__
            globals = __main__.__dict__
        if locals is None:
            locals = globals
        self.reset()
        sys.settrace(self.trace_dispatch)
        if not isinstance(expr, types.CodeType):
            expr = expr+'\n'
        try:
            return eval(expr, globals, locals)
        except BdbQuit:
            pass
        finally:
            self.quitting = 1
            sys.settrace(None) 
Example 16
Project: ironpython2   Author: IronLanguages   File: test_sys.py    License: Apache License 2.0 6 votes vote down vote up
def test_call_tracing(self):
        def f(i):
            return i * 2
        def g():
            pass

        # outside of a traceback
        self.assertEqual(10, sys.call_tracing(f, (5, )))

        # inside of a traceback
        log = []
        def thandler(frm, evt, pl):
            if evt == 'call':
                log.append(frm.f_code.co_name)
                if log[-1] == 'g':
                    sys.call_tracing(f, (5, ))
            return thandler

        sys.settrace(thandler)
        g()
        sys.settrace(None)

        self.assertEqual(log, ['g', 'f']) 
Example 17
Project: ironpython2   Author: IronLanguages   File: test_sys.py    License: Apache License 2.0 6 votes vote down vote up
def test_cp30130(self):
        def f(frame, event, arg):
            if event == 'exception':
                    global ex
                    ex = arg
            return f

        sys.settrace(f)

        def g():
            raise Exception()

        try:
            g()
        except:
            pass

        exc_type = ex[0]
        exc_value = ex[1]
        tb_value = ex[2]

        import traceback
        self.assertTrue(''.join(traceback.format_exception(exc_type, exc_value, tb_value)).find('line') != -1)

        sys.settrace(None) 
Example 18
Project: jawfish   Author: war-and-code   File: regrtest.py    License: MIT License 5 votes vote down vote up
def restore_sys_gettrace(self, trace_fxn):
        sys.settrace(trace_fxn) 
Example 19
Project: jawfish   Author: war-and-code   File: support.py    License: MIT License 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 20
Project: jawfish   Author: war-and-code   File: threading.py    License: MIT License 5 votes vote down vote up
def settrace(func):
    """Set a trace function for all threads started from the threading module.

    The func will be passed to sys.settrace() for each thread, before its run()
    method is called.

    """
    global _trace_hook
    _trace_hook = func

# Synchronization classes 
Example 21
Project: verge3d-blender-addon   Author: Soft8Soft   File: support.py    License: GNU General Public License v3.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 22
Project: verge3d-blender-addon   Author: Soft8Soft   File: profilehooks.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 23
Project: verge3d-blender-addon   Author: Soft8Soft   File: profilehooks.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 24
Project: recipes-py   Author: luci   File: debug.py    License: 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 25
Project: codimension   Author: SergeySatskiy   File: clientbase_cdm_dbg.py    License: GNU General Public License v3.0 5 votes vote down vote up
def fork(self):
        """fork routine deciding which branch to follow"""
        # It does not make sense to follow something which was run via the
        # subprocess module. The subprocess module uses fork() internally,
        # so let's analyze it and do auto follow parent even if it was not
        # required explicitly.
        isPopen = False
        stackFrames = traceback.extract_stack()
        for stackFrame in stackFrames:
            if stackFrame[2] == '_execute_child':
                if stackFrame[0].endswith(os.path.sep + 'subprocess.py'):
                    isPopen = True

        if not self.forkAuto and not isPopen:
            sendJSONCommand(self.socket, METHOD_FORK_TO,
                            self.procuuid, None)
            self.eventLoop(True)
        pid = DEBUG_CLIENT_ORIG_FORK()

        if isPopen:
            # Switch to following parent
            oldFollow = self.forkChild
            self.forkChild = False

        if pid == 0:
            # child
            if not self.forkChild:
                sys.settrace(None)
                sys.setprofile(None)
                self.sessionClose(False)
        else:
            # parent
            if self.forkChild:
                sys.settrace(None)
                sys.setprofile(None)
                self.sessionClose(False)

        if isPopen:
            # Switch to what it was before
            self.forkChild = oldFollow
        return pid 
Example 26
Project: codimension   Author: SergeySatskiy   File: base_cdm_dbg.py    License: GNU General Public License v3.0 5 votes vote down vote up
def bootstrap(self, target, args, kwargs):
        """Bootstraps a thread"""
        try:
            # Because in the initial run method the "base debug" function is
            # set up, it's also valid for the threads afterwards.
            sys.settrace(self.trace_dispatch)

            target(*args, **kwargs)
        except Exception:
            excinfo = sys.exc_info()
            self.user_exception(excinfo, True)
        finally:
            sys.settrace(None)
            sys.setprofile(None) 
Example 27
Project: codimension   Author: SergeySatskiy   File: base_cdm_dbg.py    License: GNU General Public License v3.0 5 votes vote down vote up
def run(self, cmd, globalsDict=None, localsDict=None, debug=True):
        """Starts a given command under debugger control"""
        if globalsDict is None:
            import __main__
            globalsDict = __main__.__dict__

        if localsDict is None:
            localsDict = globalsDict

        if not isinstance(cmd, types.CodeType):
            cmd = compile(cmd, "<string>", "exec")

        if debug:
            # First time the trace_dispatch function is called, a "base debug"
            # function has to be returned, which is called at every user code
            # function call. This is ensured by setting stop_everywhere.
            self.stop_everywhere = True
            sys.settrace(self.trace_dispatch)

        try:
            exec(cmd, globalsDict, localsDict)
            atexit._run_exitfuncs()
            self._dbgClient.progTerminated(0)
        except SystemExit:
            atexit._run_exitfuncs()
            excinfo = sys.exc_info()
            exitcode, message = self.__extractSystemExitMessage(excinfo)
            self._dbgClient.progTerminated(exitcode, message)
        except Exception:
            excinfo = sys.exc_info()
            self.user_exception(excinfo, True)
        finally:
            self.quitting = True
            sys.settrace(None) 
Example 28
Project: codimension   Author: SergeySatskiy   File: base_cdm_dbg.py    License: GNU General Public License v3.0 5 votes vote down vote up
def set_continue(self, special):
        """Stops only on next breakpoint"""
        # Here we only set a new stop frame if it is a normal continue.
        if not special:
            self._set_stopinfo(None, None)

        # Disable tracing if not started in debug mode
        if not self._dbgClient.debugging:
            sys.settrace(None)
            sys.setprofile(None) 
Example 29
Project: jbox   Author: jpush   File: debug.py    License: MIT License 5 votes vote down vote up
def spew(trace_names=None, show_values=False):
    """Install a trace hook which writes incredibly detailed logs
    about what code is being executed to stdout.
    """
    sys.settrace(Spew(trace_names, show_values)) 
Example 30
Project: jbox   Author: jpush   File: debug.py    License: MIT License 5 votes vote down vote up
def unspew():
    """Remove the trace hook installed by spew.
    """
    sys.settrace(None)