本文整理汇总了Python中sys._current_frames函数的典型用法代码示例。如果您正苦于以下问题:Python _current_frames函数的具体用法?Python _current_frames怎么用?Python _current_frames使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_current_frames函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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)
示例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
示例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', '?')
示例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()))
示例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\"> </td><td class=\"%s\"> </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\"> </td></tr>" % ('yes' if avail else 'no', ' ' if avail else (lock.owner or '???'), 'yes' if lock.reentrant() else 'no')
示例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__']
示例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()
示例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
示例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])
示例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()
示例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
示例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)
示例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)