• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python sys.settrace函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: handle

    def handle(self, *args, **options):
        global good_regex
        global bad_regex
        args = list(args)
        command = args.pop(0)
        global_options['include_builtins'] = options['include_builtins']
        global_options['include_stdlib'] = options['include_stdlib']
        global_options['module_only'] = options['module_only']
        global_options['calls_only'] = options['calls_only']
        global_options['good'] = options['good']
        global_options['bad'] = options['bad']
        global_options['good_regex'] = options['good_regex']
        global_options['bad_regex'] = options['bad_regex']
        global_options['good_preset'] = options['good_preset']
        global_options['bad_preset'] = options['bad_preset']

        good_regex = re.compile(global_options['good_regex'])
        bad_regex = re.compile(global_options['bad_regex'])

        sys.settrace(traceit)

        options = dict(
            use_reloader=False,
        )
        management.call_command(command, *args, **options)
开发者ID:djredhand,项目名称:phtc,代码行数:25,代码来源:trace.py


示例17: probe_func

 def probe_func( frame, event, arg ):
     if event=='return':
         l = frame.f_locals
         for key in keys:
             dictionary[key] = l.get( key )
         sys.settrace( None )
     return probe_func
开发者ID:OxES,项目名称:pyhm,代码行数:7,代码来源:InstantiationDecorators.py


示例18: __init__

 def __init__(self, *args, **kwargs):
     global tracer
     global q
     self._response_headers = []
     # print DEBUG_ENABLED
     # self.http_version = "1.1"
     DBG("START")
     # STDERR("START: debug_enable=%s"%DEBUG_ENABLED)
     if DEBUG_ENABLED:
         # STDERR("bps: %s" % tracer.get_all_breaks())
         if tracer.get_all_breaks():
             q.put("set_continue")
         tracer.set_trace()
         tracer.process_pending_commands()
         # STDERR("bps: %s" % tracer.get_all_breaks())
         # STDERR("%d" % q.unfinished_tasks)
     else:
         # Debug is not enable and there are no breakpoints
         # continue without debugger overhead
         # STDERR(repr(tracer.get_all_breaks()))
         sys.settrace(None)
     WSGIRequestHandler.__init__(self, *args, **kwargs)
     # STDOUT("aqui")
     # print self.requestline
     # print self.headers
     try:
         WSOUT("REQUEST_HEADERS", "%s\n%s\n%s" % ("-" * 20, self.requestline, self.headers))
     except AttributeError:
         pass
     DBG("STOP")
开发者ID:rayleyva,项目名称:gweb2py,代码行数:30,代码来源:gw2pserver.py


示例19: trace_dispatch

 def trace_dispatch(self, frame, event, arg):
     """
     Public method wrapping the trace_dispatch of bdb.py.
     
     It wraps the call to dispatch tracing into
     bdb to make sure we have locked the client to prevent multiple
     threads from entering the client event loop.
     
     @param frame The current stack frame.
     @param event The trace event (string)
     @param arg The arguments
     @return local trace function
     """
     try:
         self._dbgClient.lockClient()
         # if this thread came out of a lock, and we are quitting
         # and we are still running, then get rid of tracing for this thread
         if self.quitting and self._threadRunning:
             sys.settrace(None)
             sys.setprofile(None)
         import threading
         self.__name = threading.currentThread().getName()
         retval = DebugBase.trace_dispatch(self, frame, event, arg)
     finally:
         self._dbgClient.unlockClient()
     
     return retval
开发者ID:Darriall,项目名称:eric,代码行数:27,代码来源:DebugThread.py


示例20: detach

def detach():
	"""
	Finish execution tracing, print the results and reset internal state
	"""
	global _gls
	global current_gl
	global _states
	global _curr_states
	global _attach_expiration
	global _trace_began_at

	# do we have a current trace?
	if not _trace_began_at:
		return

	duration = time.time() - _trace_began_at
	_attach_expiration = None
	sys.settrace(None)
	_maybe_flush(_trace_output_file)
	_print_output(duration)
	_gls = {}
	_curr_gl = None
	_states = {}
	_curr_states = {}
	_trace_began_at = None
	curr_state = None
开发者ID:laiyonghao,项目名称:gevent-profiler,代码行数:26,代码来源:__init__.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python sys.stderr函数代码示例发布时间:2022-05-27
下一篇:
Python sys.setswitchinterval函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap