当前位置: 首页>>代码示例>>Python>>正文


Python sys.settrace函数代码示例

本文整理汇总了Python中sys.settrace函数的典型用法代码示例。如果您正苦于以下问题:Python settrace函数的具体用法?Python settrace怎么用?Python settrace使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了settrace函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: TraceFunc

    def TraceFunc(self, frame, event, arg):
        if event == 'call' and frame.f_code.co_name in ('schedule_cb', ):
            sys.settrace(self.NullTraceFunc)
            return self.ResumeTracingTraceFunc
        tasklet = stackless.current
        # print "         TraceFunc: %s %s in %s, line %s" % \
        #  (id(tasklet), event, frame.f_code.co_name, frame.f_lineno)

        ok = True
        if event in ('call', 'line', 'return'):
            key = (id(tasklet), frame.f_lineno)
            try:
                count = self.seen[key]
            except KeyError:
                ok = False
            else:
                self.seen[key] = count + 1
        else:
            ok = False
        if not ok:
            self.unexpected_trace_events.append((tasklet, event,
                                                 frame.f_code.co_name,
                                                 frame.f_lineno))

        if event in ('call', 'line', 'exception'):
            return self.TraceFunc
        return None
开发者ID:dev-alex-alex2006hw,项目名称:tools,代码行数:27,代码来源:test_tracing.py

示例2: run

 def run(self):
     # Note: this is important: we have to set the tracing function
     # when the thread is started (we could set threading.settrace
     # before starting this thread to do this externally)
     try:
         global call_finished
         sys.settrace(do_nothing_trace_function)
         exec self._Thread__kwargs['call_string'] in self._Thread__kwargs['kw']
         print "exec call finished!"
         call_finished = True
     except TypeError as t:
         call_finished = True
         self._Thread__kwargs['Exception'] = t
     except AttributeError as a:
         call_finished = True
         self._Thread__kwargs['Exception'] = a
     except SyntaxError as s1:
         call_finished = True
         self._Thread__kwargs['Exception'] = s1
     except SigFinish as sf1:
         call_finished = True
         self._Thread__kwargs['Exception'] = sf1
     except Exception as e1:
         call_finished = True
         self._Thread__kwargs['Exception'] = e1
开发者ID:pkcd,项目名称:pytest,代码行数:25,代码来源:random_gen.py

示例3: trace_process

def trace_process (**kwargs):
    
    """Literally log every line of python code as it runs.
    
    Keyword arguments:
    log -- file (name) to log to (default stderr)
    scope -- base scope to log to (default Cobalt)"""
    
    file_name = kwargs.get("log", None)
    if file_name is not None:
        log_file = open(file_name, "w")
    else:
        log_file = sys.stderr
    
    scope = kwargs.get("scope", "Cobalt")
    
    def traceit (frame, event, arg):
        if event == "line":
            lineno = frame.f_lineno
            filename = frame.f_globals["__file__"]
            if (filename.endswith(".pyc") or
                filename.endswith(".pyo")):
                filename = filename[:-1]
            name = frame.f_globals["__name__"]
            line = linecache.getline(filename, lineno)
            print >> log_file, "%s:%s: %s" % (name, lineno, line.rstrip())
        return traceit
    
    sys.settrace(traceit)
开发者ID:benmcclelland,项目名称:cobalt,代码行数:29,代码来源:Logging.py

示例4: unsettrace

    def unsettrace(self, irc, msg, args):
        """takes no arguments

        Stops tracing function calls on stdout.
        """
        sys.settrace(None)
        irc.replySuccess()
开发者ID:AssetsIncorporated,项目名称:Limnoria,代码行数:7,代码来源:plugin.py

示例5: run_and_compare

 def run_and_compare(self, func, events):
     tracer = Tracer()
     sys.settrace(tracer.trace)
     func()
     sys.settrace(None)
     self.compare_events(func.func_code.co_firstlineno,
                         tracer.events, events)
开发者ID:Britefury,项目名称:jython,代码行数:7,代码来源:test_trace.py

示例6: main

def main():
    usage = "mactrace.py [-o output_file_path] scriptfile [arg] ..."
    parser = OptionParser(usage=usage)
    parser.allow_interspersed_args = False
    parser.add_option('-o', '--outfile', dest="outfile",
                      help="Save trace to <outfile>", default=None)
    if not sys.argv[1:]:
        parser.print_usage()
        sys.exit(2)

    (options, args) = parser.parse_args()
    sys.argv[:] = args
    if options.outfile:
        twriter = TraceWriter(open(options.outfile, "w"))
    else:
        twriter = TraceWriter()
    sys.settrace(twriter.trace)
    if len(args) > 0:
        progname = args[0]
        sys.path.insert(0, os.path.dirname(progname))
        with open(progname, 'rb') as fp:
            code = compile(fp.read(), progname, 'exec')
        globs = {
            '__file__': progname,
            '__name__': '__main__',
            '__package__': None,
        }
        eval(code, globs)
    else:
        parser.print_usage()
    return parser
开发者ID:kif,项目名称:pyFAI,代码行数:31,代码来源:mactrace.py

示例7: __bootstrap

  def __bootstrap(self):
    try:
      self._set_ident()
      self._Thread__started.set()
      threading._active_limbo_lock.acquire()
      threading._active[self._Thread__ident] = self
      del threading._limbo[self]
      threading._active_limbo_lock.release()

      if threading._trace_hook:
        sys.settrace(threading._trace_hook)
      if threading._profile_hook:
        sys.setprofile(threading._profile_hook)

      try:
        self.run()
      finally:
        self._Thread__exc_clear()
    finally:
      with threading._active_limbo_lock:
        self._Thread__stop()
        try:
          del threading._active[threading._get_ident()]
        except:
          pass
开发者ID:0xmilk,项目名称:appscale,代码行数:25,代码来源:background_thread.py

示例8: test_trace_raise_three_arg

    def test_trace_raise_three_arg(self):
        import sys
        l = []
        def trace(frame, event, arg):
            if event == 'exception':
                l.append(arg)
            return trace

        def g():
            try:
                raise Exception
            except Exception as e:
                import sys
                raise Exception, e, sys.exc_info()[2]

        def f():
            try:
                g()
            except:
                pass

        sys.settrace(trace)
        f()
        sys.settrace(None)
        assert len(l) == 2
        assert issubclass(l[0][0], Exception)
        assert issubclass(l[1][0], Exception)
开发者ID:mozillazg,项目名称:pypy,代码行数:27,代码来源:test_pyframe.py

示例9: test_set_unset_f_trace

 def test_set_unset_f_trace(self):
     import sys
     seen = []
     def trace1(frame, what, arg):
         seen.append((1, frame, frame.f_lineno, what, arg))
         return trace1
     def trace2(frame, what, arg):
         seen.append((2, frame, frame.f_lineno, what, arg))
         return trace2
     def set_the_trace(f):
         f.f_trace = trace1
         sys.settrace(trace2)
         len(seen)     # take one line: should not be traced
     f = sys._getframe()
     set_the_trace(f)
     len(seen)     # take one line: should not be traced
     len(seen)     # take one line: should not be traced
     sys.settrace(None)   # and this line should be the last line traced
     len(seen)     # take one line
     del f.f_trace
     len(seen)     # take one line
     firstline = set_the_trace.func_code.co_firstlineno
     assert seen == [(1, f, firstline + 6, 'line', None),
                     (1, f, firstline + 7, 'line', None),
                     (1, f, firstline + 8, 'line', None)]
开发者ID:mozillazg,项目名称:pypy,代码行数:25,代码来源:test_pyframe.py

示例10: test_trace_return_exc

    def test_trace_return_exc(self):
        import sys
        l = []
        def trace(a,b,c):
            if b in ('exception', 'return'):
                l.append((b, c))
            return trace

        def g():
            raise Exception
        def f():
            try:
                g()
            except:
                pass
        sys.settrace(trace)
        f()
        sys.settrace(None)
        assert len(l) == 4
        assert l[0][0] == 'exception'
        assert isinstance(l[0][1][1], Exception)
        assert l[1] == ('return', None)
        assert l[2][0] == 'exception'
        assert isinstance(l[2][1][1], Exception)
        assert l[3] == ('return', None)
开发者ID:mozillazg,项目名称:pypy,代码行数:25,代码来源:test_pyframe.py

示例11: test_trace_try_finally

    def test_trace_try_finally(self):
        import sys
        l = []
        def trace(frame, event, arg):
            if event == 'exception':
                l.append(arg)
            return trace

        def g():
            try:
                raise Exception
            finally:
                pass

        def f():
            try:
                g()
            except:
                pass

        sys.settrace(trace)
        f()
        sys.settrace(None)
        assert len(l) == 2
        assert issubclass(l[0][0], Exception)
        assert issubclass(l[1][0], Exception)
开发者ID:mozillazg,项目名称:pypy,代码行数:26,代码来源:test_pyframe.py

示例12: test_trace_hidden_prints

    def test_trace_hidden_prints(self):
        import sys

        l = []
        def trace(a,b,c):
            l.append((a,b,c))
            return trace

        outputf = open(self.tempfile1, 'w')
        def f():
            print >> outputf, 1
            print >> outputf, 2
            print >> outputf, 3
            return "that's the return value"

        sys.settrace(trace)
        f()
        sys.settrace(None)
        outputf.close()
        # should get 1 "call", 3 "line" and 1 "return" events, and no call
        # or return for the internal app-level implementation of 'print'
        assert len(l) == 6
        assert [what for (frame, what, arg) in l] == [
            'call', 'line', 'line', 'line', 'line', 'return']
        assert l[-1][2] == "that's the return value"
开发者ID:mozillazg,项目名称:pypy,代码行数:25,代码来源:test_pyframe.py

示例13: start

 def start(self):
     self.get_ready()
     if self.nesting == 0:  # pragma: no cover
         sys.settrace(self.t)
         if hasattr(threading, "settrace"):
             threading.settrace(self.t)
     self.nesting += 1
开发者ID:jmbruel,项目名称:SysMLBook,代码行数:7,代码来源:coverage.py

示例14: trace_lines

def trace_lines(do_trace):
    """Turn on/off printing each executed line.

    Args:
        do_trace: Whether to start tracing (True) or stop it (False).
    """
    def trace(frame, event, arg):
        """Trace function passed to sys.settrace.

        Return:
            Itself, so tracing continues.
        """
        if sys is not None:
            loc = '{}:{}'.format(frame.f_code.co_filename, frame.f_lineno)
            if arg is not None:
                arg = utils.compact_text(str(arg), 200)
            else:
                arg = ''
            print("{:11} {:80} {}".format(event, loc, arg), file=sys.stderr)
            return trace
        else:
            # When tracing while shutting down, it seems sys can be None
            # sometimes... if that's the case, we stop tracing.
            return None
    if do_trace:
        sys.settrace(trace)
    else:
        sys.settrace(None)
开发者ID:HalosGhost,项目名称:qutebrowser,代码行数:28,代码来源:debug.py

示例15: __init__

	def __init__(self, func=None, unpack=None, **kwargs):
		self.__defs__ = []
		self.__sizes__ = []
		self.__attrs__ = []
		self.__values__ = {}
		self.__next__ = True
		self.__baked__ = False
		
		if func == None:
			self.__format__()
		else:
			sys.settrace(self.__trace__)
			func()
			for name in func.func_code.co_varnames:
				value = self.__frame__.f_locals[name]
				self.__setattr__(name, value)
		
		self.__baked__ = True
		
		if unpack != None:
			if isinstance(unpack, tuple):
				self.unpack(*unpack)
			else:
				self.unpack(unpack)
		
		if len(kwargs):
			for name in kwargs:
				self.__values__[name] = kwargs[name]
开发者ID:InfosHack,项目名称:NewerSMBW,代码行数:28,代码来源:common.py


注:本文中的sys.settrace函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。