Python sys.settrace() Examples

The following are 30 code examples of sys.settrace(). 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: test_sys.py    From ironpython2 with Apache License 2.0 7 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 #2
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 #3
Source File: base_cdm_dbg.py    From codimension with 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 #4
Source File: test_sys.py    From ironpython2 with 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 #5
Source File: bdb.py    From ironpython2 with 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 #6
Source File: bdb.py    From ironpython2 with 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 #7
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 #8
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 #9
Source File: test_sys_settrace.py    From ironpython2 with 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 #10
Source File: test_sys_settrace.py    From ironpython2 with 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 #11
Source File: test_sys_settrace.py    From ironpython2 with 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 #12
Source File: bdb.py    From meddle with 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 #13
Source File: test_scope.py    From ironpython2 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

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

        self.assertRaises(TypeError, sys.settrace) 
Example #14
Source File: test_scope.py    From ironpython2 with 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 #15
Source File: debugger.py    From ironpython2 with 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 #16
Source File: adb.py    From ironpython2 with 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 #17
Source File: __init__.py    From ironpython2 with 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 #18
Source File: test_sys_settrace.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_no_jump_without_trace_function(self):
        # Must set sys.settrace(None) in setUp(), else condition is not
        # triggered.
        no_jump_without_trace_function() 
Example #19
Source File: test_sys_settrace.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def _settrace_and_return(tracefunc):
    sys.settrace(tracefunc)
    sys._getframe().f_back.f_trace = tracefunc 
Example #20
Source File: test_sys.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_cp24381(self):
        import sys
        orig_sys_trace_func = sys.gettrace()
        def f(*args):
            global CP24381_MESSAGES
            CP24381_MESSAGES += args[1:]
            return f

        cp24381_file_name = "cp24381.py"
        cp24381_contents  = """
print 'a'
print 'b'
print 'c'

def f():
    print 'hi'

f()
"""

        try:
            self.write_to_file(cp24381_file_name, cp24381_contents)
            sys.settrace(f)
            with path_modifier('.'):
                import cp24381
        finally:
            sys.settrace(orig_sys_trace_func)
            os.unlink(cp24381_file_name)

        self.assertEqual(CP24381_MESSAGES,
                ['call', None, 'line', None, 'line', None, 'line', None, 'line',
                None, 'line', None, 'call', None, 'line', None, 'return', None,
                'return', None]) 
Example #21
Source File: tracer.py    From snoop with MIT License 5 votes vote down vote up
def __enter__(self, context=0):
        if not self.config.enabled:
            return

        calling_frame = sys._getframe(context + 1)
        if not self._is_internal_frame(calling_frame):
            calling_frame.f_trace = self.trace
            self.target_frames.add(calling_frame)
            self.config.last_frame = calling_frame
            self.trace(calling_frame, 'enter', None)

        stack = thread_global.__dict__.setdefault('original_trace_functions', [])
        stack.append(sys.gettrace())
        sys.settrace(self.trace) 
Example #22
Source File: test_threading.py    From ironpython2 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
            _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 #23
Source File: test_threading.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_finalize_with_trace(self):
        # Issue1733757
        # Avoid a deadlock when sys.settrace steps into threading._shutdown
        p = subprocess.Popen([sys.executable, "-c", """if 1:
            import sys, threading

            # A deadlock-killer, to prevent the
            # testsuite to hang forever
            def killer():
                import os, time
                time.sleep(2)
                print 'program blocked; aborting'
                os._exit(2)
            t = threading.Thread(target=killer)
            t.daemon = True
            t.start()

            # This is the trace function
            def func(frame, event, arg):
                threading.current_thread()
                return func

            sys.settrace(func)
            """],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
        self.addCleanup(p.stdout.close)
        self.addCleanup(p.stderr.close)
        stdout, stderr = p.communicate()
        rc = p.returncode
        self.assertFalse(rc == 2, "interpreted was blocked")
        self.assertTrue(rc == 0,
                        "Unexpected error: " + repr(stderr)) 
Example #24
Source File: doctest.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def set_continue(self):
        # Calling set_continue unconditionally would break unit test
        # coverage reporting, as Bdb.set_continue calls sys.settrace(None).
        if self.__debugger_used:
            pdb.Pdb.set_continue(self) 
Example #25
Source File: pdb.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def do_debug(self, arg):
        sys.settrace(None)
        globals = self.curframe.f_globals
        locals = self.curframe_locals
        p = Pdb(self.completekey, self.stdin, self.stdout)
        p.prompt = "(%s) " % self.prompt.strip()
        print >>self.stdout, "ENTERING RECURSIVE DEBUGGER"
        sys.call_tracing(p.run, (arg, globals, locals))
        print >>self.stdout, "LEAVING RECURSIVE DEBUGGER"
        sys.settrace(self.trace_dispatch)
        self.lastcmd = p.lastcmd 
Example #26
Source File: tracer.py    From snoop with MIT License 5 votes vote down vote up
def __exit__(self, exc_type, exc_value, exc_traceback, context=0):
        if not self.config.enabled:
            return

        stack = thread_global.original_trace_functions
        sys.settrace(stack.pop())
        calling_frame = sys._getframe(context + 1)
        self.trace(calling_frame, 'exit', None)
        self.target_frames.discard(calling_frame)
        self.frame_infos.pop(calling_frame, None) 
Example #27
Source File: debugger.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def run(self, cmd,globals=None, locals=None, start_stepping = 1):
		if type(cmd) not in [types.StringType, types.CodeType]:
			raise TypeError("Only strings can be run")
		self.last_cmd_debugged = cmd
		if start_stepping:
			self.isInitialBreakpoint = 0
		else:
			self.isInitialBreakpoint = 1
		try:
			if globals is None:
				import __main__
				globals = __main__.__dict__
			if locals is None:
				locals = globals
			self.reset()
			self.prep_run(cmd)
			sys.settrace(self.trace_dispatch)
			if type(cmd) != types.CodeType:
				cmd = cmd+'\n'
			try:
				try:
					if start_stepping: self.skipBotFrame = SKIP_STEP
					else: self.skipBotFrame = SKIP_RUN
					if sys.version_info > (2,2):
						exec cmd in globals, locals
					else:
						_doexec(cmd, globals, locals)
				except bdb.BdbQuit:
					pass
			finally:
				self.skipBotFrame = SKIP_NONE
				self.quitting = 1
				sys.settrace(None)

		finally:
			self.done_run(cmd) 
Example #28
Source File: doctests.py    From locality-sensitive-hashing with MIT License 5 votes vote down vote up
def set_continue(self):
        # Calling set_continue unconditionally would break unit test 
        # coverage reporting, as Bdb.set_continue calls sys.settrace(None).
        if self.__debugger_used:
            _orp.set_continue(self) 
Example #29
Source File: bdb.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def set_quit(self):
        self.stopframe = self.botframe
        self.returnframe = None
        self.quitting = 1
        sys.settrace(None)

    # Derived classes and clients can call the following methods
    # to manipulate breakpoints.  These methods return an
    # error message is something went wrong, None if all is well.
    # Set_break prints out the breakpoint line and file:lineno.
    # Call self.get_*break*() to see the breakpoints or better
    # for bp in Breakpoint.bpbynumber: if bp: bp.bpprint(). 
Example #30
Source File: regrtest.py    From jawfish with MIT License 5 votes vote down vote up
def restore_sys_gettrace(self, trace_fxn):
        sys.settrace(trace_fxn)