python类extract_tb()的实例源码

compact_tracebacks.py 文件源码 项目:goreviewpartner 作者: pnprog 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def log_traceback_from_info(exception_type, value, tb, dst=sys.stderr, skip=0):
    """Log a given exception nicely to 'dst', showing a traceback.

    dst  -- writeable file-like object
    skip -- number of traceback entries to omit from the top of the list

    """
    for line in traceback.format_exception_only(exception_type, value):
        dst.write(line)
    if (not isinstance(exception_type, str) and
        issubclass(exception_type, SyntaxError)):
        return
    print >>dst, 'traceback (most recent call last):'
    text = None
    for filename, lineno, fnname, text in traceback.extract_tb(tb)[skip:]:
        if fnname == "?":
            fn_s = "<global scope>"
        else:
            fn_s = "(%s)" % fnname
        print >>dst, "  %s:%s %s" % (filename, lineno, fn_s)
    if text is not None:
        print >>dst, "failing line:"
        print >>dst, text
qdb.py 文件源码 项目:spc 作者: whbrewer 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def user_exception(self, frame, info):
        """This function is called if an exception occurs,
        but only if we are to stop at or just below this level."""
        if self._wait_for_mainpyfile or self._wait_for_breakpoint:
            return
        extype, exvalue, trace = info
        # pre-process stack trace as it isn't pickeable (cannot be sent pure)
        msg = ''.join(traceback.format_exception(extype, exvalue, trace))
        trace = traceback.extract_tb(trace)
        title = traceback.format_exception_only(extype, exvalue)[0]
        # send an Exception notification
        msg = {'method': 'exception',
               'args': (title, extype.__name__, exvalue, trace, msg),
               'id': None}
        self.pipe.send(msg)
        self.interaction(frame, info)
test_zipimport.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def doTraceback(self, module):
        try:
            module.do_raise()
        except:
            tb = sys.exc_info()[2].tb_next

            f,lno,n,line = extract_tb(tb, 1)[0]
            self.assertEqual(line, raise_src.strip())

            f,lno,n,line = extract_stack(tb.tb_frame, 1)[0]
            self.assertEqual(line, raise_src.strip())

            s = io.StringIO()
            print_tb(tb, 1, s)
            self.assertTrue(s.getvalue().endswith(raise_src))
        else:
            raise AssertionError("This ought to be impossible")
run.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def print_exception():
    import linecache
    linecache.checkcache()
    flush_stdout()
    efile = sys.stderr
    typ, val, tb = excinfo = sys.exc_info()
    sys.last_type, sys.last_value, sys.last_traceback = excinfo
    tbe = traceback.extract_tb(tb)
    print('Traceback (most recent call last):', file=efile)
    exclude = ("run.py", "rpc.py", "threading.py", "queue.py",
               "RemoteDebugger.py", "bdb.py")
    cleanup_traceback(tbe, exclude)
    traceback.print_list(tbe, file=efile)
    lines = traceback.format_exception_only(typ, val)
    for line in lines:
        print(line, end='', file=efile)
gu.py 文件源码 项目:Solfege 作者: RannyeriDev 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def display_exception_message(exception, lessonfile=None):
        """Call this function only inside an except clause."""
        sourcefile, lineno, func, code = traceback.extract_tb(sys.exc_info()[2])[0]
        # We can replace characters because we will only display the
        # file name, not open the file.
        sourcefile = sourcefile.decode(sys.getfilesystemencoding(), 'replace')
        m = ExceptionDialog(exception)
        if lessonfile:
            m.add_text(_("Please check the lesson file %s.") % lessonfile)

        if sourcefile:
            m.add_text(_('The exception was caught in\n"%(filename)s", line %(lineno)i.') % {'filename': sourcefile, 'lineno': lineno})

        if 'm_nonwrapped_text' in dir(exception):
            m.add_nonwrapped_text(exception.m_nonwrapped_text)
        m.run()
        m.destroy()
excepts.py 文件源码 项目:fandango 作者: tango-controls 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def getPreviousExceptions(limit=0):
    """
    sys.exc_info() returns : type,value,traceback
    traceback.extract_tb(traceback) :  returns (filename, line number, function name, text)
    """
    try:
        exinfo = sys.exc_info()
        if exinfo[0] is not None:
            stack = traceback.format_tb(exinfo[2])
            return str('\n'.join(['Tracebacks (most recent call last):',
                                ''.join(stack[(len(stack)>1 and 1 or 0):]),
                                ': '.join([str(exinfo[0].__name__),str(exinfo[1])])
                                ]))
        else:
            return ''
    except Exception,e:
        print 'Aaaargh!'
        return traceback.format_exc()
qdb.py 文件源码 项目:Problematica-public 作者: TechMaz 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def user_exception(self, frame, info):
        """This function is called if an exception occurs,
        but only if we are to stop at or just below this level."""
        if self._wait_for_mainpyfile or self._wait_for_breakpoint:
            return
        extype, exvalue, trace = info
        # pre-process stack trace as it isn't pickeable (cannot be sent pure)
        msg = ''.join(traceback.format_exception(extype, exvalue, trace))
        trace = traceback.extract_tb(trace)
        title = traceback.format_exception_only(extype, exvalue)[0]
        # send an Exception notification
        msg = {'method': 'exception',
               'args': (title, extype.__name__, exvalue, trace, msg),
               'id': None}
        self.pipe.send(msg)
        self.interaction(frame, info)
test_zipimport.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def doTraceback(self, module):
        try:
            module.do_raise()
        except:
            tb = sys.exc_info()[2].tb_next

            f,lno,n,line = extract_tb(tb, 1)[0]
            self.assertEqual(line, raise_src.strip())

            f,lno,n,line = extract_stack(tb.tb_frame, 1)[0]
            self.assertEqual(line, raise_src.strip())

            s = StringIO.StringIO()
            print_tb(tb, 1, s)
            self.assertTrue(s.getvalue().endswith(raise_src))
        else:
            raise AssertionError("This ought to be impossible")
code.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list)
run.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def print_exception():
    import linecache
    linecache.checkcache()
    flush_stdout()
    efile = sys.stderr
    typ, val, tb = excinfo = sys.exc_info()
    sys.last_type, sys.last_value, sys.last_traceback = excinfo
    tbe = traceback.extract_tb(tb)
    print>>efile, '\nTraceback (most recent call last):'
    exclude = ("run.py", "rpc.py", "threading.py", "Queue.py",
               "RemoteDebugger.py", "bdb.py")
    cleanup_traceback(tbe, exclude)
    traceback.print_list(tbe, file=efile)
    lines = traceback.format_exception_only(typ, val)
    for line in lines:
        print>>efile, line,
test_zipimport.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def doTraceback(self, module):
        try:
            module.do_raise()
        except:
            tb = sys.exc_info()[2].tb_next

            f,lno,n,line = extract_tb(tb, 1)[0]
            self.assertEqual(line, raise_src.strip())

            f,lno,n,line = extract_stack(tb.tb_frame, 1)[0]
            self.assertEqual(line, raise_src.strip())

            s = StringIO.StringIO()
            print_tb(tb, 1, s)
            self.assertTrue(s.getvalue().endswith(raise_src))
        else:
            raise AssertionError("This ought to be impossible")
code.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            list = traceback.format_list(tblist)
            if list:
                list.insert(0, "Traceback (most recent call last):\n")
            list[len(list):] = traceback.format_exception_only(type, value)
        finally:
            tblist = tb = None
        map(self.write, list)
run.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def print_exception():
    import linecache
    linecache.checkcache()
    flush_stdout()
    efile = sys.stderr
    typ, val, tb = excinfo = sys.exc_info()
    sys.last_type, sys.last_value, sys.last_traceback = excinfo
    tbe = traceback.extract_tb(tb)
    print>>efile, '\nTraceback (most recent call last):'
    exclude = ("run.py", "rpc.py", "threading.py", "Queue.py",
               "RemoteDebugger.py", "bdb.py")
    cleanup_traceback(tbe, exclude)
    traceback.print_list(tbe, file=efile)
    lines = traceback.format_exception_only(typ, val)
    for line in lines:
        print>>efile, line,
models.py 文件源码 项目:django-errorlog 作者: yjmade 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def from_except(cls, name, tb, exception, error_html_getter=None, error_html_getter_params={}, **data):
        try:
            from celery.exceptions import Retry
        except ImportError:
            pass
        else:
            if isinstance(exception, Retry):
                six.reraise(Retry, exception, tb)
        tb_stacks = traceback.extract_tb(tb)
        stack_list = [
            (cls._normalize_file_python(src_path), lineno, func_name, src_code)
            for src_path, lineno, func_name, src_code in tb_stacks
        ]
        error_html_getter = error_html_getter or (lambda exc_type, exc_value, tb, **kwargs: Reporter(exc_type, exc_value, tb).get_traceback_html())
        data[cls.name_property] = name
        res = cls(
            stack_hash=cls._get_stack_hash(stack_list),
            error_type=cls._get_except_cls_name(type(exception)),
            error_html=error_html_getter(exc_type=type(exception), exc_value=exception, tb=tb, **error_html_getter_params),
            **data
        )
        res.stack_list = stack_list
        res.error_args = [repr(arg) for arg in exception.args]
        return res
SConscript.py 文件源码 项目:StatisKit 作者: StatisKit 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def SConscript_exception(file=sys.stderr):
    """Print an exception stack trace just for the SConscript file(s).
    This will show users who have Python errors where the problem is,
    without cluttering the output with all of the internal calls leading
    up to where we exec the SConscript."""
    exc_type, exc_value, exc_tb = sys.exc_info()
    tb = exc_tb
    while tb and stack_bottom not in tb.tb_frame.f_locals:
        tb = tb.tb_next
    if not tb:
        # We did not find our exec statement, so this was actually a bug
        # in SCons itself.  Show the whole stack.
        tb = exc_tb
    stack = traceback.extract_tb(tb)
    try:
        type = exc_type.__name__
    except AttributeError:
        type = str(exc_type)
        if type[:11] == "exceptions.":
            type = type[11:]
    file.write('%s: %s:\n' % (type, exc_value))
    for fname, line, func, text in stack:
        file.write('  File "%s", line %d:\n' % (fname, line))
        file.write('    %s\n' % text)
Main.py 文件源码 项目:StatisKit 作者: StatisKit 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def find_deepest_user_frame(tb):
    """
    Find the deepest stack frame that is not part of SCons.

    Input is a "pre-processed" stack trace in the form
    returned by traceback.extract_tb() or traceback.extract_stack()
    """

    tb.reverse()

    # find the deepest traceback frame that is not part
    # of SCons:
    for frame in tb:
        filename = frame[0]
        if filename.find(os.sep+'SCons'+os.sep) == -1:
            return frame
    return tb[0]
web_server_service.py 文件源码 项目:shakecast 作者: usgs 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def main():
        logging.info(' ** Starting ShakeCast Web Server ** ')
        try:
            start()

        except Exception as e:
            logging.info('FAILED')
            exc_tb = sys.exc_info()[2]
            filename, line_num, func_name, text = traceback.extract_tb(exc_tb)[-1]
            logging.info('{}: {} - line: {}\nOriginated: {} {} {} {}'.format(type(e), 
                                                                             e, 
                                                                             exc_tb.tb_lineno,
                                                                             filename, 
                                                                             line_num, 
                                                                             func_name, 
                                                                             text))
        return
server_service.py 文件源码 项目:shakecast 作者: usgs 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def main():
        logging.info(' ** Starting ShakeCast Server ** ')
        try:
            sc_server = Server()

            # start shakecast
            sc_server.start_shakecast()

            while sc_server.stop_server is False:
                sc_server.stop_loop = False
                sc_server.loop()

        except Exception as e:
            exc_tb = sys.exc_info()[2]
            filename, line_num, func_name, text = traceback.extract_tb(exc_tb)[-1]
            logging.info('{}: {} - line: {}\nOriginated: {} {} {} {}'.format(type(e), 
                                                                             e, 
                                                                             exc_tb.tb_lineno,
                                                                             filename, 
                                                                             line_num, 
                                                                             func_name, 
                                                                             text))
        return
web_server_service.py 文件源码 项目:shakecast 作者: usgs 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def main():
        logging.info(' ** Starting ShakeCast Web Server ** ')
        try:
            start()

        except Exception as e:
            exc_tb = sys.exc_info()[2]
            filename, line_num, func_name, text = traceback.extract_tb(exc_tb)[-1]
            logging.info('{}: {} - line: {}\nOriginated: {} {} {} {}'.format(type(e), 
                                                                             e, 
                                                                             exc_tb.tb_lineno,
                                                                             filename, 
                                                                             line_num, 
                                                                             func_name, 
                                                                             text))
        return
server_service.py 文件源码 项目:shakecast 作者: usgs 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def main():
        logging.info(' ** Starting ShakeCast Server ** ')
        try:
            sc_server = Server()

            # start shakecast
            sc_server.start_shakecast()

            while sc_server.stop_server is False:
                sc_server.stop_loop = False
                sc_server.loop()

        except Exception as e:
            exc_tb = sys.exc_info()[2]
            filename, line_num, func_name, text = traceback.extract_tb(exc_tb)[-1]
            logging.info('{}: {} - line: {}\nOriginated: {} {} {} {}'.format(type(e), 
                                                                             e, 
                                                                             exc_tb.tb_lineno,
                                                                             filename, 
                                                                             line_num, 
                                                                             func_name, 
                                                                             text))
        return


问题


面经


文章

微信
公众号

扫码关注公众号