我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sys.gettrace()。
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)
def test_element_cyclic_gc_none(self): # test if cyclic reference can crash etree Element = self.etree.Element # must disable tracing as it could change the refcounts trace_func = sys.gettrace() try: sys.settrace(None) gc.collect() count = sys.getrefcount(None) l = [Element('name'), Element('name')] l.append(l) del l gc.collect() self.assertEqual(sys.getrefcount(None), count) finally: sys.settrace(trace_func)
def callTool(self, args): """Call the raspbian-qemu tool with a check for a kept root.img.""" # Clean up any root images so we can assert whether it's created # or not after the run. if os.path.exists(self.ROOT_IMG): os.unlink(self.ROOT_IMG) cmd = [TOOL] # Assume any time the trace function is set it's coverage and make # sure to spawn the tool under coverage as well. if sys.gettrace(): cmd = ["python3-coverage", "run", "--parallel-mode"] + cmd subprocess.check_output(cmd + args, stderr=subprocess.STDOUT) # Now make sure root.img was created if request but not if it wasn't. # If created correctly, check its state and then clean it up. keep_root = "--keep-root" in args self.assertEqual(os.path.exists(self.ROOT_IMG), keep_root) if keep_root: self.assertOnlyUserReadable(self.ROOT_IMG) os.unlink(self.ROOT_IMG)
def _sim_aftercare(self): # reset internal states self._sim_settings = None # delete modules for module in self._sim_modules.keys(): del module self._sim_modules = {} # don't disconnect signals in debug-mode if sys.gettrace() is None: self.simThread.started.disconnect(self._worker.run) self._worker.state_changed.disconnect(self.simulation_state_changed) self._worker.work_done.disconnect(self.simThread.quit) self.simThread.finished.disconnect(self.thread_finished) # delete simulator self._logger.info("deleting simulator") del self._worker
def test_ipdb_magics2(): '''Test ipdb with a very short function. >>> old_trace = sys.gettrace() >>> def bar(): ... pass Run ipdb. >>> with PdbTestInput([ ... 'continue', ... ]): ... debugger.Pdb().runcall(bar) > <doctest ...>(2)bar() 1 def bar(): ----> 2 pass <BLANKLINE> ipdb> continue Restore previous trace function, e.g. for coverage.py >>> sys.settrace(old_trace) '''
def can_quit(): '''Test that quit work in ipydb >>> old_trace = sys.gettrace() >>> def bar(): ... pass >>> with PdbTestInput([ ... 'quit', ... ]): ... debugger.Pdb().runcall(bar) > <doctest ...>(2)bar() 1 def bar(): ----> 2 pass <BLANKLINE> ipdb> quit Restore previous trace function, e.g. for coverage.py >>> sys.settrace(old_trace) '''
def can_exit(): '''Test that quit work in ipydb >>> old_trace = sys.gettrace() >>> def bar(): ... pass >>> with PdbTestInput([ ... 'exit', ... ]): ... debugger.Pdb().runcall(bar) > <doctest ...>(2)bar() 1 def bar(): ----> 2 pass <BLANKLINE> ipdb> exit Restore previous trace function, e.g. for coverage.py >>> sys.settrace(old_trace) '''
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.
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)
def log_lines(): current_file = inspect.getframeinfo(sys._getframe(1)).filename pprint('Tracing is ON in %r' % current_file) def tracer(frame, event, arg): if event != 'line': return tracer info = inspect.getframeinfo(frame) code = info.code_context[0] if info.code_context else '' if info.filename == current_file: pprint('Executing %s:%s %s' % (info.filename, info.lineno, code)) return tracer old_trace = sys.gettrace() def restore(): sys.settrace(old_trace) sys.settrace(tracer) return restore
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)
def test_remote_python_process(): in_debug_mode = sys.gettrace() is not None p = RemotePythonProcess( function=partial(my_func, a=1, b=2), ip_address='localhost', ) stdin , stdout, stderr = p.execute_child_process() time.sleep(.1) # That autta be enough errtext = stderr.read() if in_debug_mode: assert errtext.startswith('pydev debugger: ') else: assert errtext == '', errtext assert stdout.read() == 'hello hello hello\n' assert p.get_return_value()==3
def no_tracing(f): @functools.wraps(f) def wrapper(*args, **kwargs): trace_func = sys.gettrace() try: sys.settrace(None) threading.settrace(None) return f(*args, **kwargs) finally: sys.settrace(trace_func) threading.settrace(trace_func) return wrapper
def stop(self): """Stop this Tracer.""" self.stopped = True if self.thread != threading.currentThread(): # Called on a different thread than started us: we can't unhook # ourseves, but we've set the flag that we should stop, so we won't # do any more tracing. 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(),)) #print("Stopping tracer on %s" % threading.current_thread().ident) sys.settrace(None)
def start(self): """Start collecting trace information.""" if self._collectors: self._collectors[-1].pause() self._collectors.append(self) #print("Started: %r" % self._collectors, file=sys.stderr) # Check to see whether we had a fullcoverage tracer installed. traces0 = [] if hasattr(sys, "gettrace"): fn0 = sys.gettrace() if fn0: tracer0 = getattr(fn0, '__self__', None) if tracer0: traces0 = getattr(tracer0, 'traces', []) # Install the tracer on this thread. fn = self._start_tracer() 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. threading.settrace(self._installation_trace)
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
def test_set_and_retrieve_none(self): sys.settrace(None) assert sys.gettrace() is None
def test_set_and_retrieve_func(self): def fn(*args): pass sys.settrace(fn) try: assert sys.gettrace() is fn finally: sys.settrace(None)
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)
def __init__(self, run=True, *, _frame=1): """ set _frame to 2 if you are inherting from ConditionalBlock and __enter__() is nested. Set _frame to N+1 for N levels of nesting. See `DebugBlock.__enter__` """ self.run = run self.old_sys_trace = sys.gettrace() self._frame = _frame
def __enter__(self): self.real_stdin = sys.stdin sys.stdin = _FakeInput(self.input) self.orig_trace = sys.gettrace() if hasattr(sys, 'gettrace') else None
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
def get_sys_gettrace(self): return sys.gettrace()
def setUp(self): self.addCleanup(sys.settrace, sys.gettrace())
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").
def setUp(self): self.addCleanup(sys.settrace, sys.gettrace()) sys.settrace(None)
def setUp(self): self.my_py_filename = fix_ext_py(__file__) self.addCleanup(sys.settrace, sys.gettrace())