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

Python sys._current_frames函数代码示例

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

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



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

示例1: wrapped

 def wrapped(*args, **kwargs):
   old_threads = set(sys._current_frames().keys())
   res = func(*args, **kwargs)
   new_threads = set(sys._current_frames().keys())
   new_threads -= old_threads
   global_exclude_thread_ids.update(new_threads)
   return res
开发者ID:chagge,项目名称:returnn,代码行数:7,代码来源:Debug.py


示例2: metrics

    def metrics(self):
        metrics = {}

        # get total threads
        metrics['totalThreads'] = len(sys._current_frames().keys())

        # get free threads
        freeThreads = 0
        for frame in sys._current_frames().values():
            _self = frame.f_locals.get('self')
            if getattr(_self, '__module__', None) == ZRendevous.__module__:
                freeThreads += 1
        metrics['freeThreads'] = freeThreads

        try:
            metrics['activeSessions'] = len(self.context.unrestrictedTraverse('/temp_folder/session_data'))
        except Exception:
            metrics['activeSessions'] = -1
            
        global _REQUEST_TOTAL, _REQUEST_COUNT, _REQUEST_TIME
        metrics["requestTotal"] = _REQUEST_TOTAL
        metrics["request1m"] = max(_REQUEST_COUNT.query(60), 1)
        metrics["requestTimeAvg1m"] = _REQUEST_TIME.query(60) / float(metrics["request1m"])
        
        for key, value in self._getVmStats():
            metrics[key] = value
            
        return metrics
开发者ID:SteelHouseLabs,项目名称:zenoss-prodbin,代码行数:28,代码来源:stats.py


示例3: do_frame

    def do_frame(self, arg):
        """frame [thread-Name|thread-number] [frame-number]
Move the current frame to the specified frame number. If a
Thread-Name is given, move the current frame to that. Dot (.) can be used
to indicate the name of the current frame. A thread number can be used
in Python 2.5 or greater.

0 is the most recent frame. A negative number indicates position from
the other end.  So 'frame -1' moves when gdb dialect is in
effect moves to the oldest frame, and 'frame 0' moves to the
newest frame."""
        args = arg.split()
        if len(args) > 0:
            thread_name = args[0]
            try:
                thread_id = int(thread_name)
                if hasattr(sys, '_current_frames'):
                    threads = sys._current_frames()
                    if thread_id not in threads.keys():
                        self.errmsg("I don't know about thread number %s" %
                                    thread_name)
                        self.info_thread_terse()
                        return
                    frame = threads[thread_id]
                    newframe = find_nondebug_frame(self, frame)
                    if newframe is not None:  frame = newframe
                    self.stack, self.curindex = self.get_stack(frame, None)
                    if len(args) == 1:
                        arg = '0'
                    else:
                        arg = ' '.join(args[1:])
            except ValueError:
                # Must be frame command without a frame number
                if thread_name == '.':
                    thread_name = threading.currentThread().getName()
                if thread_name not in self.traced.keys():
                     self.errmsg("I don't know about thread %s" % thread_name)
                     return
                thread_id = self.traced[thread_name]
                if hasattr(sys, '_current_frames'):
                    frames = sys._current_frames()
                    if thread_id in frames.keys():
                        self.curframe_thread_name = thread_name
                        frame                     = frames[thread_id]
                else:
                    self.errmsg("Frame selection not supported. Upgrade to")
                    self.errmsg("Python 2.5 or install threadframe.")
                    return

                newframe = find_nondebug_frame(self, frame)
                if newframe is not None:  frame = newframe
                self.stack, self.curindex = self.get_stack(frame, None)
                if len(args) == 1:
                    arg = '0'
                else:
                    arg = ' '.join(args[1:])

        self.thread_name = threading.currentThread().getName()

        pydb.Pdb.do_frame(self, arg)
开发者ID:gsliu,项目名称:emacs_C,代码行数:60,代码来源:threaddbg.py


示例4: streaming

    def streaming(self):
        next_call = time.time() 
        while not self.stopped.wait(next_call - time.time()):  #timer compensate

            self.x=self.x+1
            self.s.send(self.input_update)
            print "have sent update command to streamer.."
        #                         print "recv data1 from streamer.."
            resp1 = self.s.recv(1024*10)
        #                         print "received simu's data1:",resp1
            print "received data from streamer!!"
            xdata["1"].append(self.x)
            xdata["2"].append(self.x)
        #             print resp1,"dd"
            resp_A=resp1.split('\n')[0]
            resp_B=resp1.split('\n')[1]
            
            rexp = re.compile(r'[^\d.,]+')
            data1=map(float,rexp.sub('', resp_A).split(','))[1]
            data2=map(float,rexp.sub('', resp_B).split(','))[1]
            ydata["1"].append(data1)
            ydata["2"].append(data2)
        
            thread2.on_running(xdata, ydata)
            print sys._current_frames()
            next_call = next_call+1  #timer=1s
开发者ID:liangcai2012,项目名称:savant-torrey-ranch,代码行数:26,代码来源:socket_Q_server.py


示例5: test_current_frames

    def test_current_frames(self):
        import sys
        import time
        import thread

        # XXX workaround for now: to prevent deadlocks, call
        # sys._current_frames() once before starting threads.
        # This is an issue in non-translated versions only.
        sys._current_frames()

        thread_id = thread.get_ident()
        def other_thread():
            print "thread started"
            lock2.release()
            lock1.acquire()
        lock1 = thread.allocate_lock()
        lock2 = thread.allocate_lock()
        lock1.acquire()
        lock2.acquire()
        thread.start_new_thread(other_thread, ())

        def f():
            lock2.acquire()
            return sys._current_frames()

        frames = f()
        lock1.release()
        thisframe = frames.pop(thread_id)
        assert thisframe.f_code.co_name in ('f', '?')

        assert len(frames) == 1
        _, other_frame = frames.popitem()
        assert other_frame.f_code.co_name in ('other_thread', '?')
开发者ID:yuyichao,项目名称:pypy,代码行数:33,代码来源:test_sysmodule.py


示例6: __dumpstacks

    def __dumpstacks(self, context=1, sighandler_deep=2):
        """ Signal handler: dump a stack trace for each existing thread."""

        currentThreadId = threading.currentThread().ident

        def unique_count(l):
            d = collections.defaultdict(lambda: 0)
            for v in l:
                d[tuple(v)] += 1
            return list((k, v) for k, v in d.items())

        stack_displays = []
        for threadId, stack in sys._current_frames().items():
            stack_display = []
            for filename, lineno, name, line in traceback.extract_stack(stack):
                stack_display.append('  File: "%s", line %d, in %s'
                                     % (filename, lineno, name))
                if line:
                    stack_display.append("    %s" % (line.strip()))
            if currentThreadId == threadId:
                stack_display = stack_display[:- (sighandler_deep * 2)]
                stack_display.append('  => Stopped to handle current signal. ')
            stack_displays.append(stack_display)
        stacks = unique_count(stack_displays)
        self.ui.debug('thread', "** Thread List:\n")
        for stack, times in stacks:
            if times == 1:
                msg = "%s Thread is at:\n%s\n"
            else:
                msg = "%s Threads are at:\n%s\n"
            self.ui.debug('thread', msg % (times, '\n'.join(stack[- (context * 2):])))

        self.ui.debug('thread', "Dumped a total of %d Threads." %
                      len(sys._current_frames().keys()))
开发者ID:ordnungswidrig,项目名称:offlineimap,代码行数:34,代码来源:init.py


示例7: adminInfo

def adminInfo(handler):
	handler.title('Information')
	requirePriv(handler, 'Admin')

	print "<div class=\"info\">"

	print "<h3>Uptime</h3>"
	loadTime = getLoadtime()
	print "Started %s<br>" % loadTime
	print "Up for %s<br>" % timesince(loadTime)
	print "Total requests: %d<br>" % server().getTotalRequests()
	print "<form method=\"post\" action=\"/admin/restart\">"
	print Button('Restart', type = 'submit').negative()
	print "</form>"

	print "<h3>Threads</h3>"
	print "<table border=\"1\" cellspacing=\"0\" cellpadding=\"4\">"
	print "<tr><th>ID</th><th class=\"main\">Name</th><th>Alive</th><th>Daemon</th></tr>"
	for thread in sorted(threads(), key = lambda thread: thread.name):
		print "<tr><td>%s</td><td>" % ('None' if thread.ident is None else "%x" % abs(thread.ident))
		print thread.name
		print "<br>"
		try:
			print CollapsibleBox('Traceback', formatTrace(traceback.extract_stack(sys._current_frames()[thread.ident])))
		except Exception:
			pass
		print "</td><td class=\"%s\">&nbsp;</td><td class=\"%s\">&nbsp;</td></tr>" % ('yes' if thread.isAlive() else 'no', 'yes' if thread.daemon else 'no')
	print "</table>"

	print "<h3>Locks</h3>"
	print "<table border=\"1\" cellspacing=\"0\" cellpadding=\"4\">"
	print "<tr><th class=\"main\">Name</th><th>Available</th><th>Reentrant</th></tr>"
	for (name, lock) in sorted(locks.iteritems()):
		print "<tr><td>"
		print name
		avail = lock.avail()
		if not avail:
			print "<br>"
			writer = ResponseWriter()
			try:
				owner, tb = lock.owner, lock.tb
				name = ("%x" % abs(owner)) if owner else 'None'
				#TODO Is there no O(1) way to do this?
				for thread in threads():
					if thread.ident == owner:
						name = "%s (%x)" % (thread.name, abs(owner))
						break
				print "Owned by: <b>%s</b><br><br>" % name
				if tb:
					print "Acquisition traceback:<br>"
					print formatTrace(tb)
					print "<br>"
				print "Current traceback:<br>"
				print formatTrace(traceback.extract_stack(sys._current_frames()[owner]))
			except Exception, e:
				writer.clear()
				print "<i>(Unable to retrieve stack trace)</i>"
			print CollapsibleBox('Ownership', writer.done())
		print "</td><td class=\"%s\">%s</td><td class=\"%s\">&nbsp;</td></tr>" % ('yes' if avail else 'no', '&nbsp;' if avail else (lock.owner or '???'), 'yes' if lock.reentrant() else 'no')
开发者ID:mrozekma,项目名称:Sprint,代码行数:59,代码来源:admin.py


示例8: getCallingModuleName

def getCallingModuleName():
    import sys
    if sys.version_info[0] == 3:
        f = list(sys._current_frames().values())[0]
    else:
        f = sys._current_frames().values()[0]
    f = f.f_back
    return f.f_back.f_globals['__name__']
开发者ID:kdbanman,项目名称:browseRDF,代码行数:8,代码来源:tulipqtplugins.py


示例9: synthesize_thread_stacks

 def synthesize_thread_stacks():
   threads = dict([(th.ident, th) for th in threading.enumerate()])
   ostr = StringIO()
   if len(sys._current_frames()) > 1 or (
       sys._current_frames().values()[0] != inspect.currentframe()):
     # Multi-threaded
     ostr.write('\nAll threads:\n')
     for thread_id, stack in sys._current_frames().items():
       AppExceptionHandler.print_stack(thread_id, threads[thread_id], stack, ostr, indent=2)
   return ostr.getvalue()
开发者ID:billwei,项目名称:commons,代码行数:10,代码来源:exception_handler.py


示例10: info_thread_missing

 def info_thread_missing(self):
     """Show information about threads we might not know about"""
     if hasattr(sys, "_current_frames") and \
            len(self.traced) != len(sys._current_frames()):
         frames = sys._current_frames()
         thread_ids = frames.keys()
         self.msg("Untraced/unknown threads:")
         for thread_id in thread_ids:
             if thread_id not in self.traced.values():
                 self.msg("\t%d" % thread_id)
     return
开发者ID:gsliu,项目名称:emacs_C,代码行数:11,代码来源:threaddbg.py


示例11: test_top_frame

    def test_top_frame(self):
        self.assertEqual(1, len(sys._current_frames()))

        frame = sys._current_frames().items()[0][1]

        # frame filename and name
        self.assertEqual((frame.f_code.co_filename, frame.f_code.co_name),
                         _snakemeter.get_top_frame()[:2])

        # line number of current frame
        self.assertEqual(sys._current_frames().items()[0][1].f_lineno, _snakemeter.get_top_frame()[2])
开发者ID:gchp,项目名称:snakemeter,代码行数:11,代码来源:test_native.py


示例12: synthesize_thread_stacks

 def synthesize_thread_stacks():
   threads = dict([(th.ident, th) for th in threading.enumerate()])
   ostr = Compatibility.StringIO()
   # _current_frames not yet implemented on pypy and not guaranteed anywhere but
   # cpython in practice.
   if hasattr(sys, '_current_frames') and (len(sys._current_frames()) > 1 or
       sys._current_frames().values()[0] != inspect.currentframe()):
     # Multi-threaded
     ostr.write('\nAll threads:\n')
     for thread_id, stack in sys._current_frames().items():
       BasicExceptionHandler.print_stack(thread_id, threads[thread_id], stack, ostr, indent=2)
   return ostr.getvalue()
开发者ID:BabyDuncan,项目名称:commons,代码行数:12,代码来源:__init__.py


示例13: info_thread_missing

def info_thread_missing(obj):
    """Show information about threads we might not know about"""
    if not hasattr(obj, "traced"): return
    if (hasattr(sys, "_current_frames") and 
        len(obj.traced) != len(sys._current_frames())):
        frames = sys._current_frames()
        thread_ids = frames.keys()
        obj.msg("Untraced/unknown threads:")
        for thread_id in thread_ids:
            if thread_id not in obj.traced.values():
                obj.msg("\t%d" % thread_id)
    return
开发者ID:carlgao,项目名称:lenga,代码行数:12,代码来源:threadinfo.py


示例14: dumpThread

def dumpThread(threadId):
	import sys
	if not hasattr(sys, "_current_frames"):
		print "Warning: dumpThread: no sys._current_frames"
		return
	
	if threadId not in sys._current_frames():
		print("Thread %d not found" % threadId)
		return
	
	stack = sys._current_frames()[threadId]
	better_exchook.print_traceback(stack)
开发者ID:BMXE,项目名称:music-player,代码行数:12,代码来源:utils.py


示例15: dumpThread

def dumpThread(threadId):
	import threading, sys, traceback
	if threadId not in sys._current_frames():
		print "Thread", threadId, "not found"
		return
	
	code = []
	stack = sys._current_frames()[threadId]
	for filename, lineno, name, line in traceback.extract_stack(stack):
		code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
		if line:
			code.append("  %s" % (line.strip()))
	print "\n".join(code)
开发者ID:gijs,项目名称:music-player,代码行数:13,代码来源:utils.py


示例16: getCallingModuleName

def getCallingModuleName():
  import sys
  if sys.version_info[0] == 3:
    frames = list(sys._current_frames().values())
  else:
    frames = sys._current_frames().values()
  for i in range(len(frames)):
    f = frames[i]
    if f.f_globals['__name__'] == "tulipplugins":
      f = f.f_back
      break
  while f.f_globals['__name__'] == "tulipplugins":
    f = f.f_back
  return f.f_globals['__name__']
开发者ID:tulip5,项目名称:tulip,代码行数:14,代码来源:tulipplugins.py


示例17: wrapped

 def wrapped(*args, **kwargs):
   """
   :param args:
   :param kwargs:
   :return:
   """
   # noinspection PyProtectedMember
   old_threads = set(sys._current_frames().keys())
   res = func(*args, **kwargs)
   # noinspection PyProtectedMember
   new_threads = set(sys._current_frames().keys())
   new_threads -= old_threads
   global_exclude_thread_ids.update(new_threads)
   return res
开发者ID:rwth-i6,项目名称:returnn,代码行数:14,代码来源:Debug.py


示例18: debug_dump_threads

def debug_dump_threads():
    print("\n===== %s dump thread stack frames. %i threads. conductor lock = %s:\n" % (
        format_unixts(time.time()),
        len(sys._current_frames()),
        the_conductor.lock), file=sys.stderr)
    idx=0
    for thread_id, frame in sys._current_frames().items():
        print("===== thread #%i [%#x] refcount = %s" % (idx, thread_id, sys.getrefcount(frame)), file=sys.stderr)
        if thread_id != _debug_thread_id:
            traceback.print_stack(frame, file = sys.stderr)
        else:
            print("  debug thread, skipping", file=sys.stderr)
        idx += 1
    print("=====\n", file=sys.stderr)
开发者ID:mickours,项目名称:execo,代码行数:14,代码来源:conductor.py


示例19: save_transaction

    def save_transaction(self, transaction):
        """Saves the specified transaction away under the thread ID of
        the current executing thread. Will also cache a reference to the
        greenlet if using coroutines. This is so we can later determine
        the stack trace for a transaction when using greenlets.

        """

        thread_id = transaction.thread_id

        if thread_id in self._cache:
            raise RuntimeError('transaction already active')

        self._cache[thread_id] = transaction

        # We judge whether we are actually running in a coroutine by
        # seeing if the current thread ID is actually listed in the set
        # of all current frames for executing threads. If we are
        # executing within a greenlet, then thread.get_ident() will
        # return the greenlet identifier. This will not be a key in
        # dictionary of all current frames because that will still be
        # the original standard thread which all greenlets are running
        # within.

        transaction._greenlet = None

        if hasattr(sys, '_current_frames'):
            if thread_id not in sys._current_frames():
                greenlet = sys.modules.get('greenlet')
                if greenlet:
                    transaction._greenlet = weakref.ref(greenlet.getcurrent())
开发者ID:Mause,项目名称:table_select_web,代码行数:31,代码来源:transaction_cache.py


示例20: cry

def cry():  # pragma: no cover
    """Return stacktrace of all active threads.

    From https://gist.github.com/737056

    """
    tmap = {}
    main_thread = None
    # get a map of threads by their ID so we can print their names
    # during the traceback dump
    for t in threading.enumerate():
        if getattr(t, "ident", None):
            tmap[t.ident] = t
        else:
            main_thread = t

    out = StringIO()
    sep = "=" * 49 + "\n"
    for tid, frame in sys._current_frames().iteritems():
        thread = tmap.get(tid, main_thread)
        out.write("%s\n" % (thread.getName(),))
        out.write(sep)
        traceback.print_stack(frame, file=out)
        out.write(sep)
        out.write("LOCAL VARIABLES\n")
        out.write(sep)
        pprint(frame.f_locals, stream=out)
        out.write("\n\n")
    return out.getvalue()
开发者ID:ackdesha,项目名称:celery,代码行数:29,代码来源:__init__.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python sys._exc_info函数代码示例发布时间:2022-05-27
下一篇:
Python sys._clear_type_cache函数代码示例发布时间: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