sys._current_frames

Here are the examples of the python api sys._current_frames taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

76 Examples 7

Example 1

Project: music-player
Source File: utils.py
View license
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)

Example 2

Project: canvas
Source File: debug.py
View license
    def sample(self):
        t = time.time()
        frames = sys._current_frames()
        my_frame = sys._getframe()
        for thread, frame in frames.items():
            if frame == my_frame:
                continue
                                
            if '/gunicorn/' in frame.f_code.co_filename:
                continue
                
            header = "Stack Monitor pid: %s time: %s thread: %s\n" % (self.pid, t, thread)
            self.output.write(header + "".join(traceback.format_stack(frame)))

Example 3

Project: pympler
Source File: web.py
View license
@bottle.route('/traceback/:threadid')
@bottle.view('stacktrace')
def get_traceback(threadid):
    threadid = int(threadid)
    frames = sys._current_frames()
    if threadid in frames:
        frame = frames[threadid]
        stack = getouterframes(frame, 5)
        stack.reverse()
        stack = [(get_ref(f[0].f_locals),) + f[1:] for f in stack]
    else:
        stack = []
    return dict(stack=stack, threadid=threadid)

Example 4

Project: pyxmpp2
Source File: _support.py
View license
    def stack_dumper():
        stackdump_file = open(os.environ.get("TEST_STACKDUMP_FILE"), "w")
        while True:
            time.sleep(5)
            stackdump_file.write(time.ctime() + "\n")
            frames = sys._current_frames()
            for frame in frames.values():
                traceback.print_stack(frame, file = stackdump_file)
            stackdump_file.write("\n")
            stackdump_file.flush()

Example 5

Project: TrustRouter
Source File: test_sys.py
View license
    def current_frames_without_threads(self):
        # Not much happens here:  there is only one thread, with artificial
        # "thread id" 0.
        d = sys._current_frames()
        self.assertEqual(len(d), 1)
        self.assertIn(0, d)
        self.assertTrue(d[0] is sys._getframe())

Example 6

Project: support
Source File: context.py
View license
    def _thread_spin_monitor(self):
        while 1:
            time.sleep(0.05)
            if not self.ctx.tracing or self is not self.MAIN_INSTANCE:
                return
            if not self.last_spin:
                continue
            ct = faststat.nanotime()
            dur = ct - self.last_spin
            # if time is greater than 150 ms
            if dur > 150e6 and time.time() - self.last_cal_log > 1:
                tid = self.main_thread_id
                frame = sys._current_frames()[tid]
                # specifically dont log pdb
                if frame.f_code is not cmd.Cmd.cmdloop.im_func.func_code:
                    stack = _format_stack(frame)
                    self.ctx.log.info('LONG_SPIN').failure(time=dur/1e6,
                                                           slow_green=stack)
                self.last_cal_log = time.time()

Example 7

Project: txstatsd
Source File: report.py
View license
    def dump_frames(self):
        """Dump frames info to log file."""
        current = threading.currentThread().ident
        frames = sys._current_frames()
        for frame_id, frame in frames.iteritems():
            if frame_id == current:
                continue

            stack = ''.join(traceback.format_stack(frame))

            if frame_id == self.reactor_thread:
                title = "Dumping Python frame for reactor main thread"
            else:
                title = "Dumping Python frame"
            self.log("%s %s (pid: %d):\n%s" %
                     (title, frame_id, os.getpid(), stack),
                     logLevel=logging.DEBUG)

Example 8

Project: pox
Source File: debug_deadlock.py
View license
def _trace_thread_proc ():
  try:
    while core.running:
      frames = sys._current_frames()
      for key in frames:
        frame = frames[key]
        print inspect.getframeinfo(frame)
        outer_frames = inspect.getouterframes(frame)
        for i in range(0, len(outer_frames)):
          print "     " + str(inspect.getframeinfo(outer_frames[i][0]))

      time.sleep(5)
  except:
    traceback.print_exc()

Example 9

View license
    def iter_frames(self, t):
        #sys._current_frames(): dictionary with thread id -> topmost frame
        current_frames = sys._current_frames()
        v = current_frames.get(t.ident)
        if v is not None:
            return [v]
        return []

Example 10

Project: mishkal
Source File: watchthreads.py
View license
def traceback_thread(thread_id):
    """
    Returns a plain-text traceback of the given thread, or None if it
    can't get a traceback.
    """
    if not hasattr(sys, '_current_frames'):
        # Only 2.5 has support for this, with this special function
        return None
    frames = sys._current_frames()
    if not thread_id in frames:
        return None
    frame = frames[thread_id]
    out = StringIO()
    traceback.print_stack(frame, file=out)
    return out.getvalue()

Example 11

Project: RouteFlow
Source File: debug_deadlock.py
View license
def _trace_thread_proc ():
  try:
    while core.running:
      frames = sys._current_frames()
      for key in frames:
        frame = frames[key]
        print inspect.getframeinfo(frame)
        outer_frames = inspect.getouterframes(frame)
        for i in range(0, len(outer_frames)): 
          print "     " + str(inspect.getframeinfo(outer_frames[i][0]))

      time.sleep(5)
  except:
    traceback.print_exc()

Example 12

Project: brython
Source File: test_sys.py
View license
    def current_frames_without_threads(self):
        # Not much happens here:  there is only one thread, with artificial
        # "thread id" 0.
        d = sys._current_frames()
        self.assertEqual(len(d), 1)
        self.assertIn(0, d)
        self.assertTrue(d[0] is sys._getframe())

Example 13

Project: brozzler
Source File: easy.py
View license
    def dump_state(self, signum=None, frame=None):
        state_strs = []
        for th in threading.enumerate():
            state_strs.append(str(th))
            stack = traceback.format_stack(sys._current_frames()[th.ident])
            state_strs.append(''.join(stack))
        logging.warn('dumping state (caught signal {})\n{}'.format(
            signum, '\n'.join(state_strs)))

Example 14

Project: pprofile
Source File: pprofile.py
View license
    def run(self):
        current_frames = sys._current_frames
        test = self._test
        if test is None:
            test = lambda x, ident=self.ident: ident != x
        sample = self._profiler.sample
        stop_event = self._stop_event
        wait = partial(stop_event.wait, self._period)
        while self._can_run:
            for ident, frame in current_frames().iteritems():
                if test(ident):
                    sample(frame)
            frame = None
            wait()
        stop_event.clear()
        self.clean_exit = True

Example 15

Project: PyAutoC
Source File: test_sys.py
View license
    def current_frames_without_threads(self):
        # Not much happens here:  there is only one thread, with artificial
        # "thread id" 0.
        d = sys._current_frames()
        self.assertEqual(len(d), 1)
        self.assertIn(0, d)
        self.assertTrue(d[0] is sys._getframe())

Example 16

Project: shiji
Source File: report.py
View license
    def dump_frames(self):
        """Dump frames info to log file."""
        current = threading.currentThread().ident
        frames = sys._current_frames()
        for frame_id, frame in frames.iteritems():
            if frame_id == current:
                continue

            stack = ''.join(traceback.format_stack(frame))

            if frame_id == self.reactor_thread:
                title = "Dumping Python frame for reactor main thread"
            else:
                title = "Dumping Python frame"
            self.log("%s %s (pid: %d):\n%s" %
                     (title, frame_id, os.getpid(), stack),
                     logLevel=logging.DEBUG)

Example 17

Project: pox
Source File: debug_deadlock.py
View license
def _trace_thread_proc ():
  try:
    while core.running:
      frames = sys._current_frames()
      for key in frames:
        frame = frames[key]
        print inspect.getframeinfo(frame)
        outer_frames = inspect.getouterframes(frame)
        for i in range(0, len(outer_frames)):
          print "     " + str(inspect.getframeinfo(outer_frames[i][0]))

      time.sleep(5)
  except:
    traceback.print_exc()

Example 18

Project: rdiffweb
Source File: main.py
View license
def debug_dump_thread():
    """
    Called when receiving a debug signal.
    Dump all thread stack in stdout.
    """
    for th in threading.enumerate():
        print(th)
        traceback.print_stack(sys._current_frames()[th.ident])
        print()

Example 19

Project: sync-engine
Source File: instrumentation.py
View license
    def _check_blocking(self):
        if self._switch_flag is False:
            active_greenlet = self._active_greenlet
            if active_greenlet is not None and active_greenlet != self._hub:
                # greenlet.gr_frame doesn't work on another thread -- we have
                # to get the main thread's frame.
                frame = sys._current_frames()[self._main_thread_id]
                formatted_frame = '\t'.join(traceback.format_stack(frame))
                self.log.warning(
                    'greenlet blocking', frame=formatted_frame,
                    context=getattr(active_greenlet, 'context', None),
                    blocking_greenlet_id=id(active_greenlet))
        self._switch_flag = False

Example 20

Project: mishkal
Source File: watchthreads.py
View license
def traceback_thread(thread_id):
    """
    Returns a plain-text traceback of the given thread, or None if it
    can't get a traceback.
    """
    if not hasattr(sys, '_current_frames'):
        # Only 2.5 has support for this, with this special function
        return None
    frames = sys._current_frames()
    if not thread_id in frames:
        return None
    frame = frames[thread_id]
    out = StringIO()
    traceback.print_stack(frame, file=out)
    return out.getvalue()

Example 21

Project: iot-utilities
Source File: test_sys.py
View license
    def current_frames_without_threads(self):
        # Not much happens here:  there is only one thread, with artificial
        # "thread id" 0.
        d = sys._current_frames()
        self.assertEqual(len(d), 1)
        self.assertIn(0, d)
        self.assertTrue(d[0] is sys._getframe())

Example 22

View license
    def iter_frames(self, t):
        #sys._current_frames(): dictionary with thread id -> topmost frame
        current_frames = sys._current_frames()
        v = current_frames.get(t.ident)
        if v is not None:
            return [v]
        return []

Example 23

Project: iot-utilities
Source File: test_sys.py
View license
    def current_frames_without_threads(self):
        # Not much happens here:  there is only one thread, with artificial
        # "thread id" 0.
        d = sys._current_frames()
        self.assertEqual(len(d), 1)
        self.assertIn(0, d)
        self.assertTrue(d[0] is sys._getframe())

Example 24

Project: chipsec
Source File: test_sys.py
View license
    def current_frames_without_threads(self):
        # Not much happens here:  there is only one thread, with artificial
        # "thread id" 0.
        d = sys._current_frames()
        self.assertEqual(len(d), 1)
        self.assertIn(0, d)
        self.assertTrue(d[0] is sys._getframe())

Example 25

Project: mom
Source File: StackDumper.py
View license
    def dump(self):
        try:
            stacks = sys._current_frames()
        except AttributeError:
            try:
                stacks = threadframe.dict()
            except:
                self.logger.debug("Stack dumping not supported")
                return

        for (id, stack) in stacks.items():
            msg = "Stack trace for thread %i\n" % id
            msg = msg + ''.join(traceback.format_stack(stack))
            self.logger.debug(msg)

Example 26

Project: filesync-server
Source File: reactor.py
View license
    def dump_frames(self):
        """Dump frames info to log file."""
        current = threading.currentThread().ident
        frames = sys._current_frames()
        for frame_id, frame in frames.iteritems():
            if frame_id == current:
                continue

            stack = ''.join(traceback.format_stack(frame))

            if frame_id == self.reactor_thread:
                title = "Dumping Python frame for reactor main thread"
            else:
                title = "Dumping Python frame"
            self.logger.debug("%s %s (pid: %d):\n%s",
                              title, frame_id, os.getpid(), stack)

Example 27

Project: drawquest-web
Source File: debug.py
View license
    def sample(self):
        t = time.time()
        frames = sys._current_frames()
        my_frame = sys._getframe()
        for thread, frame in frames.items():
            if frame == my_frame:
                continue
                                
            if '/gunicorn/' in frame.f_code.co_filename:
                continue
                
            header = "Stack Monitor pid: %s time: %s thread: %s\n" % (self.pid, t, thread)
            self.output.write(header + "".join(traceback.format_stack(frame)))

Example 28

Project: openwrt-mt7620
Source File: test_sys.py
View license
    def current_frames_without_threads(self):
        # Not much happens here:  there is only one thread, with artificial
        # "thread id" 0.
        d = sys._current_frames()
        self.assertEqual(len(d), 1)
        self.assertIn(0, d)
        self.assertTrue(d[0] is sys._getframe())

Example 29

View license
    def iter_frames(self, t):
        #sys._current_frames(): dictionary with thread id -> topmost frame
        current_frames = sys._current_frames()
        v = current_frames.get(t.ident)
        if v is not None:
            return [v]
        return []

Example 30

Project: oslo.middleware
Source File: __init__.py
View license
    @staticmethod
    def _get_threadstacks():
        threadstacks = []
        try:
            active_frames = sys._current_frames()
        except AttributeError:
            pass
        else:
            buf = six.StringIO()
            for stack in six.itervalues(active_frames):
                traceback.print_stack(stack, file=buf)
                threadstacks.append(buf.getvalue())
                buf.seek(0)
                buf.truncate()
        return threadstacks

Example 31

Project: iot-utilities
Source File: test_sys.py
View license
    def current_frames_without_threads(self):
        # Not much happens here:  there is only one thread, with artificial
        # "thread id" 0.
        d = sys._current_frames()
        self.assertEqual(len(d), 1)
        self.assertIn(0, d)
        self.assertTrue(d[0] is sys._getframe())

Example 32

Project: mishkal
Source File: watchthreads.py
View license
def traceback_thread(thread_id):
    """
    Returns a plain-text traceback of the given thread, or None if it
    can't get a traceback.
    """
    if not hasattr(sys, '_current_frames'):
        # Only 2.5 has support for this, with this special function
        return None
    frames = sys._current_frames()
    if not thread_id in frames:
        return None
    frame = frames[thread_id]
    out = StringIO()
    traceback.print_stack(frame, file=out)
    return out.getvalue()

Example 33

Project: datafari
Source File: test_sys.py
View license
    def current_frames_without_threads(self):
        # Not much happens here:  there is only one thread, with artificial
        # "thread id" 0.
        d = sys._current_frames()
        self.assertEqual(len(d), 1)
        self.assertIn(0, d)
        self.assertTrue(d[0] is sys._getframe())

Example 34

Project: openwrt-mt7620
Source File: test_sys.py
View license
    def current_frames_without_threads(self):
        # Not much happens here:  there is only one thread, with artificial
        # "thread id" 0.
        d = sys._current_frames()
        self.assertEqual(len(d), 1)
        self.assertIn(0, d)
        self.assertTrue(d[0] is sys._getframe())

Example 35

Project: nylas-production-python
Source File: debug.py
View license
    def _check_blocking(self):
        if self._switch_flag is False:
            active_greenlet = self._active_greenlet
            if active_greenlet is not None and active_greenlet != self._hub:
                # greenlet.gr_frame doesn't work on another thread -- we have
                # to get the main thread's frame.
                frame = sys._current_frames()[self._main_thread_id]
                formatted_frame = '\t'.join(traceback.format_stack(frame))
                self.log.warning(
                    'greenlet blocking', frame=formatted_frame,
                    context=getattr(active_greenlet, 'context', None),
                    blocking_greenlet_id=id(active_greenlet))
        self._switch_flag = False

Example 36

Project: iot-utilities
Source File: test_sys.py
View license
    def current_frames_without_threads(self):
        # Not much happens here:  there is only one thread, with artificial
        # "thread id" 0.
        d = sys._current_frames()
        self.assertEqual(len(d), 1)
        self.assertIn(0, d)
        self.assertTrue(d[0] is sys._getframe())

Example 37

Project: mishkal
Source File: watchthreads.py
View license
def traceback_thread(thread_id):
    """
    Returns a plain-text traceback of the given thread, or None if it
    can't get a traceback.
    """
    if not hasattr(sys, '_current_frames'):
        # Only 2.5 has support for this, with this special function
        return None
    frames = sys._current_frames()
    if not thread_id in frames:
        return None
    frame = frames[thread_id]
    out = StringIO()
    traceback.print_stack(frame, file=out)
    return out.getvalue()

Example 38

Project: pychess
Source File: debug.py
View license
def dump_threads():
    # This may cause random crashes
    # https://github.com/pychess/pychess/issues/1023
    stacks = []
    for thread in threading.enumerate():
        frame = sys._current_frames()[thread.ident]
        stack = traceback.format_list(traceback.extract_stack(frame))
        stacks.append("Thread: %s (%d)" % (thread.name, thread.ident))
        stacks.append("".join(stack))

    log.debug("\n" + "\n".join(stacks))

Example 39

Project: pymo
Source File: test_sys.py
View license
    def current_frames_without_threads(self):
        # Not much happens here:  there is only one thread, with artificial
        # "thread id" 0.
        d = sys._current_frames()
        self.assertEqual(len(d), 1)
        self.assertIn(0, d)
        self.assertTrue(d[0] is sys._getframe())

Example 40

Project: TrustRouter
Source File: test_sys.py
View license
    @test.support.reap_threads
    def current_frames_with_threads(self):
        import threading, _thread
        import traceback

        # Spawn a thread that blocks at a known place.  Then the main
        # thread does sys._current_frames(), and verifies that the frames
        # returned make sense.
        entered_g = threading.Event()
        leave_g = threading.Event()
        thread_info = []  # the thread's id

        def f123():
            g456()

        def g456():
            thread_info.append(_thread.get_ident())
            entered_g.set()
            leave_g.wait()

        t = threading.Thread(target=f123)
        t.start()
        entered_g.wait()

        # At this point, t has finished its entered_g.set(), although it's
        # impossible to guess whether it's still on that line or has moved on
        # to its leave_g.wait().
        self.assertEqual(len(thread_info), 1)
        thread_id = thread_info[0]

        d = sys._current_frames()

        main_id = _thread.get_ident()
        self.assertIn(main_id, d)
        self.assertIn(thread_id, d)

        # Verify that the captured main-thread frame is _this_ frame.
        frame = d.pop(main_id)
        self.assertTrue(frame is sys._getframe())

        # Verify that the captured thread frame is blocked in g456, called
        # from f123.  This is a litte tricky, since various bits of
        # threading.py are also in the thread's call stack.
        frame = d.pop(thread_id)
        stack = traceback.extract_stack(frame)
        for i, (filename, lineno, funcname, sourceline) in enumerate(stack):
            if funcname == "f123":
                break
        else:
            self.fail("didn't find f123() on thread's call stack")

        self.assertEqual(sourceline, "g456()")

        # And the next record must be for g456().
        filename, lineno, funcname, sourceline = stack[i+1]
        self.assertEqual(funcname, "g456")
        self.assertIn(sourceline, ["leave_g.wait()", "entered_g.set()"])

        # Reap the spawned thread.
        leave_g.set()
        t.join()

Example 41

Project: music-player
Source File: utils.py
View license
def debugGetThreadStack(threadName):
	th = debugFindThread(threadName)
	assert th, "thread not found"
	stack = sys._current_frames()[th.ident]
	return th, stack

Example 42

Project: python3-trepan
Source File: frame.py
View license
    def get_from_thread_name_or_id(self, name_or_id, report_error=True):
        '''See if *name_or_id* is either a thread name or a thread id.
        The frame of that id/name is returned, or None if name_or_id is
        invalid.'''
        thread_id = self.proc.get_int_noerr(name_or_id)
        if thread_id is None:
            # Must be a "frame" command with frame name, not a frame
            # number (or invalid command).
            name2id = Mthread.map_thread_names()
            if name_or_id == '.':
                name_or_id = Mthread.current_thread_name()
                pass
            thread_id = name2id.get(name_or_id)
            if thread_id is None:
                self.errmsg("I don't know about thread name %s." %
                            name_or_id)
                return None, None
            pass
        # Above we should have set thread_id. Now see if we can
        # find it.
        threads   = sys._current_frames()
        frame     = threads.get(thread_id)
        if frame is None and report_error:
            self.errmsg("I don't know about thread number %s (%d)." %
                        name_or_id, thread_id)
            # self.info_thread_terse()
            return None, None
        return frame, thread_id

Example 43

Project: ReadableWebProxy
Source File: stuck.py
View license
def handler(signum, frame):
	for th in threading.enumerate():
		print("Dumping stack for thread: ", th)
		traceback.print_stack(sys._current_frames()[th.ident])
		print()

Example 44

Project: HomeCoolingPi
Source File: hanging_threads.py
View license
def monitor():
    self = get_ident()
    old_threads = {}
    while 1:
        time.sleep(1. / TESTS_PER_SECOND)
        now = time.time()
        then = now - SECONDS_FROZEN
        frames = sys._current_frames()
        new_threads = {}
        for frame_id, frame in frames.items():
            new_threads[frame_id] = thread2list(frame)
        for thread_id, frame_list in new_threads.items():
            if thread_id == self: continue
            if thread_id not in old_threads or \
               frame_list != old_threads[thread_id][0]:
                new_threads[thread_id] = (frame_list, now)
            elif old_threads[thread_id][1] < then:
                print_frame_list(frame_list, frame_id)
            else:
                new_threads[thread_id] = old_threads[thread_id]
        old_threads = new_threads

Example 45

Project: datafari
Source File: test_sys.py
View license
    @test.test_support.reap_threads
    def current_frames_with_threads(self):
        import threading, thread
        import traceback

        # Spawn a thread that blocks at a known place.  Then the main
        # thread does sys._current_frames(), and verifies that the frames
        # returned make sense.
        entered_g = threading.Event()
        leave_g = threading.Event()
        thread_info = []  # the thread's id

        def f123():
            g456()

        def g456():
            thread_info.append(thread.get_ident())
            entered_g.set()
            leave_g.wait()

        t = threading.Thread(target=f123)
        t.start()
        entered_g.wait()

        # At this point, t has finished its entered_g.set(), although it's
        # impossible to guess whether it's still on that line or has moved on
        # to its leave_g.wait().
        self.assertEqual(len(thread_info), 1)
        thread_id = thread_info[0]

        d = sys._current_frames()

        main_id = thread.get_ident()
        self.assertIn(main_id, d)
        self.assertIn(thread_id, d)

        # Verify that the captured main-thread frame is _this_ frame.
        frame = d.pop(main_id)
        self.assertTrue(frame is sys._getframe())

        # Verify that the captured thread frame is blocked in g456, called
        # from f123.  This is a litte tricky, since various bits of
        # threading.py are also in the thread's call stack.
        frame = d.pop(thread_id)
        stack = traceback.extract_stack(frame)
        for i, (filename, lineno, funcname, sourceline) in enumerate(stack):
            if funcname == "f123":
                break
        else:
            self.fail("didn't find f123() on thread's call stack")

        self.assertEqual(sourceline, "g456()")

        # And the next record must be for g456().
        filename, lineno, funcname, sourceline = stack[i+1]
        self.assertEqual(funcname, "g456")
        self.assertIn(sourceline, ["leave_g.wait()", "entered_g.set()"])

        # Reap the spawned thread.
        leave_g.set()
        t.join()

Example 46

Project: python3-trepan
Source File: threads.py
View license
    def run(self, args):
        # FIXME: add thread locking here?

        self.thread_name = Mthread.current_thread_name()

        name2id = Mthread.map_thread_names()
        # invert threading._active
        for thread_id in list(threading._active.keys()):
            thread = threading._active[thread_id]
            name = thread.getName()
            if name not in list(self.name2id.keys()):
                self.name2id[name] = thread_id
                pass
            pass

        all_verbose = False
        if len(args) == 1:
            if args[0].startswith('verbose'):
                all_verbose = True
            elif args[0].startswith('terse'):
                self.info_thread_terse(name2id)
                return
            pass

        if len(args) > 0 and not all_verbose:
            thread_name = args[0]
            if thread_name == '.':
                thread_name = self.thread_name
            try:
                thread_id = int(thread_name)
                if thread_id not in list(threading._active.keys()):
                    self.errmsg("Don't know about thread number %s" %
                                thread_name)
                    self.info_thread_terse(name2id)
                    return
            except ValueError:
                if thread_name not in list(self.name2id.keys()):
                    self.errmsg("Don't know about thread %s" % thread_name)
                    self.info_thread_terse(name2id)
                    return
                thread_id = self.name2id[thread_name]
                pass

            frame = sys._current_frames()[thread_id]
            self.stack_trace(frame)
            return

        # Show info about *all* threads
        thread_key_list = list(self.name2id.keys())
        thread_key_list.sort()
        for thread_name in thread_key_list:
            thread_id = self.name2id[thread_name]
            frame = sys._current_frames()[thread_id]
            s = ''
            # Print location where thread was created and line number
            if thread_id in threading._active:
                thread = threading._active[thread_id]
                thread_name = thread.getName()
                if thread_name == self.proc.frame_thread_name:
                    prefix = '-> '
                    if not self.settings['dbg_trepan']:
                        frame = Mthread.find_debugged_frame(frame)
                        pass
                    pass
                elif thread_name == self.proc.thread_name:
                    prefix = '=> '
                else:
                    prefix='   '
                    pass
                s += "%s%s" % (prefix, str(thread))
                if all_verbose:
                    s += ": %d" % thread_id
                    pass
            else:
                s += "    thread id: %d" % thread_id
                pass
            s += "\n    "
            s += Mstack.format_stack_entry(self, (frame, frame.f_lineno),
                                           color=self.settings['highlight'])
            self.section('-' * 40)
            self.msg(s)
            frame = frame.f_back
            if all_verbose and frame:
                self.stack_trace(frame)
                pass
        return

Example 47

Project: profiling
Source File: samplers.py
View license
    @staticmethod
    def current_frames():
        return sys._current_frames()

Example 48

Project: mysql-tools
Source File: http_handlers.py
View license
def HandlePyThreads(unused_request, response):
  """Renders /pythreads page with Python thread stacks."""
  response.headers.add_header('Content-Type', 'text/plain')
  response.start_response(200)

  frames = sys._current_frames()
  threads = [(t.ident, t) for t in threading.enumerate()]
  thread_names = dict((tid, '(name: %s) ' % t.getName()) for tid, t in threads)

  response.out.write('Python threads:\n\n')
  for thread_id, frame in frames.items():
    response.out.write('--- Thread %d %sstack: ---\n' %
                       (thread_id, thread_names.get(thread_id, '')))
    frame_tuples = []
    while frame:
      filename = frame.f_code.co_filename
      lineno = frame.f_lineno
      line = linecache.getline(filename, lineno)
      frame_tuples.append((filename, lineno, frame.f_code.co_name, line))
      frame = frame.f_back
    frame_tuples.reverse()
    response.out.write(''.join(traceback.format_list(frame_tuples)))
  response.end_response()

Example 49

Project: DataflowPythonSDK
Source File: batchworker.py
View license
  def status_server(self):
    """Executes the serving loop for the status server."""

    class StatusHttpHandler(BaseHTTPServer.BaseHTTPRequestHandler):
      """HTTP handler for serving stacktraces of all worker threads."""

      def do_GET(self):  # pylint: disable=invalid-name
        """Return /threadz information for any GET request."""
        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.end_headers()
        frames = sys._current_frames()  # pylint: disable=protected-access
        for t in threading.enumerate():
          self.wfile.write('--- Thread #%s name: %s ---\n' % (t.ident, t.name))
          self.wfile.write(''.join(traceback.format_stack(frames[t.ident])))

      def log_message(self, f, *args):
        """Do not log any messages."""
        pass

    httpd = BaseHTTPServer.HTTPServer(
        ('localhost', self.STATUS_HTTP_PORT), StatusHttpHandler)
    logging.info('Status HTTP server running at %s:%s', httpd.server_name,
                 httpd.server_port)
    httpd.serve_forever()

Example 50

Project: openwrt-mt7620
Source File: test_sys.py
View license
    @test.test_support.reap_threads
    def current_frames_with_threads(self):
        import threading, thread
        import traceback

        # Spawn a thread that blocks at a known place.  Then the main
        # thread does sys._current_frames(), and verifies that the frames
        # returned make sense.
        entered_g = threading.Event()
        leave_g = threading.Event()
        thread_info = []  # the thread's id

        def f123():
            g456()

        def g456():
            thread_info.append(thread.get_ident())
            entered_g.set()
            leave_g.wait()

        t = threading.Thread(target=f123)
        t.start()
        entered_g.wait()

        # At this point, t has finished its entered_g.set(), although it's
        # impossible to guess whether it's still on that line or has moved on
        # to its leave_g.wait().
        self.assertEqual(len(thread_info), 1)
        thread_id = thread_info[0]

        d = sys._current_frames()

        main_id = thread.get_ident()
        self.assertIn(main_id, d)
        self.assertIn(thread_id, d)

        # Verify that the captured main-thread frame is _this_ frame.
        frame = d.pop(main_id)
        self.assertTrue(frame is sys._getframe())

        # Verify that the captured thread frame is blocked in g456, called
        # from f123.  This is a litte tricky, since various bits of
        # threading.py are also in the thread's call stack.
        frame = d.pop(thread_id)
        stack = traceback.extract_stack(frame)
        for i, (filename, lineno, funcname, sourceline) in enumerate(stack):
            if funcname == "f123":
                break
        else:
            self.fail("didn't find f123() on thread's call stack")

        self.assertEqual(sourceline, "g456()")

        # And the next record must be for g456().
        filename, lineno, funcname, sourceline = stack[i+1]
        self.assertEqual(funcname, "g456")
        self.assertIn(sourceline, ["leave_g.wait()", "entered_g.set()"])

        # Reap the spawned thread.
        leave_g.set()
        t.join()