Python traceback 模块,py() 实例源码

我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用traceback.py()

项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def get_records(self, etb, number_of_lines_of_context, tb_offset):
        try:
            # Try the default getinnerframes and Alex's: Alex's fixes some
            # problems, but it generates empty tracebacks for console errors
            # (5 blanks lines) where none should be returned.
            return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
        except UnicodeDecodeError:
            # This can occur if a file's encoding magic comment is wrong.
            # I can't see a way to recover without duplicating a bunch of code
            # from the stdlib traceback module. --TK
            error('\nUnicodeDecodeError while processing traceback.\n')
            return None
        except:
            # FIXME: I've been getting many crash reports from python 2.3
            # users, traceable to inspect.py.  If I can find a small test-case
            # to reproduce this, I should either write a better workaround or
            # file a bug report against inspect (if that's the real problem).
            # So far, I haven't been able to find an isolated example to
            # reproduce the problem.
            inspect_error()
            traceback.print_exc(file=self.ostream)
            info('\nUnfortunately, your original traceback can not be constructed.\n')
            return None
项目:FLASH    作者:yuyuz    | 项目源码 | 文件源码
def load_experiment_config_file():
    # Load the config file, this holds information about data, black box fn etc.
    try:
        cfg_filename = "config.cfg"
        config = SafeConfigParser(allow_no_value=True)
        config.read(cfg_filename)
        if not config.has_option("HPOLIB", "is_not_original_config_file"):
            logger.critical("Config file in directory %s seems to be an"
                " original config which was not created by wrapping.py. "
                "Are you sure that you are in the right directory?" %
                            os.getcwd())
            sys.exit(1)
        return config
    except IOError as e:
        logger.critical("Could not open config file in directory %s",
                        os.getcwd())
        sys.exit(1)
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def get_records(self, etb, number_of_lines_of_context, tb_offset):
        try:
            # Try the default getinnerframes and Alex's: Alex's fixes some
            # problems, but it generates empty tracebacks for console errors
            # (5 blanks lines) where none should be returned.
            return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
        except UnicodeDecodeError:
            # This can occur if a file's encoding magic comment is wrong.
            # I can't see a way to recover without duplicating a bunch of code
            # from the stdlib traceback module. --TK
            error('\nUnicodeDecodeError while processing traceback.\n')
            return None
        except:
            # FIXME: I've been getting many crash reports from python 2.3
            # users, traceable to inspect.py.  If I can find a small test-case
            # to reproduce this, I should either write a better workaround or
            # file a bug report against inspect (if that's the real problem).
            # So far, I haven't been able to find an isolated example to
            # reproduce the problem.
            inspect_error()
            traceback.print_exc(file=self.ostream)
            info('\nUnfortunately, your original traceback can not be constructed.\n')
            return None
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def get_records(self, etb, number_of_lines_of_context, tb_offset):
        try:
            # Try the default getinnerframes and Alex's: Alex's fixes some
            # problems, but it generates empty tracebacks for console errors
            # (5 blanks lines) where none should be returned.
            return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
        except:
            # FIXME: I've been getting many crash reports from python 2.3
            # users, traceable to inspect.py.  If I can find a small test-case
            # to reproduce this, I should either write a better workaround or
            # file a bug report against inspect (if that's the real problem).
            # So far, I haven't been able to find an isolated example to
            # reproduce the problem.
            inspect_error()
            traceback.print_exc(file=self.ostream)
            info('\nUnfortunately, your original traceback can not be constructed.\n')
            return None
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def get_records(self, etb, number_of_lines_of_context, tb_offset):
        try:
            # Try the default getinnerframes and Alex's: Alex's fixes some
            # problems, but it generates empty tracebacks for console errors
            # (5 blanks lines) where none should be returned.
            return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
        except UnicodeDecodeError:
            # This can occur if a file's encoding magic comment is wrong.
            # I can't see a way to recover without duplicating a bunch of code
            # from the stdlib traceback module. --TK
            error('\nUnicodeDecodeError while processing traceback.\n')
            return None
        except:
            # FIXME: I've been getting many crash reports from python 2.3
            # users, traceable to inspect.py.  If I can find a small test-case
            # to reproduce this, I should either write a better workaround or
            # file a bug report against inspect (if that's the real problem).
            # So far, I haven't been able to find an isolated example to
            # reproduce the problem.
            inspect_error()
            traceback.print_exc(file=self.ostream)
            info('\nUnfortunately, your original traceback can not be constructed.\n')
            return None
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def _fixed_getinnerframes(etb, context=1, tb_offset=0):
    LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5

    records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
    # If the error is at the console, don't build any context, since it would
    # otherwise produce 5 blank lines printed out (there is no file at the
    # console)
    rec_check = records[tb_offset:]
    try:
        rname = rec_check[0][1]
        if rname == '<ipython console>' or rname.endswith('<string>'):
            return rec_check
    except IndexError:
        pass

    aux = traceback.extract_tb(etb)
    assert len(records) == len(aux)
    for i, (file, lnum, _, _) in enumerate(aux):
        maybeStart = lnum - 1 - context // 2
        start = max(maybeStart, 0)
        end = start + context
        lines = linecache.getlines(file)[start:end]
        buf = list(records[i])
        buf[LNUM_POS] = lnum
        buf[INDEX_POS] = lnum - 1 - start
        buf[LINES_POS] = lines
        records[i] = tuple(buf)
    return records[tb_offset:]

# Helper function -- largely belongs to VerboseTB, but we need the same
# functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
# can be recognized properly by ipython.el's py-traceback-line-re
# (SyntaxErrors have to be treated specially because they have no traceback)
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def _format_list(self, extracted_list):
        """Format a list of traceback entry tuples for printing.

        Given a list of tuples as returned by extract_tb() or
        extract_stack(), return a list of strings ready for printing.
        Each string in the resulting list corresponds to the item with the
        same index in the argument list.  Each string ends in a newline;
        the strings may contain internal newlines as well, for those items
        whose source text line is not None.

        Lifted almost verbatim from traceback.py
        """

        Colors = self.Colors
        list = []
        for filename, lineno, name, line in extracted_list[:-1]:
            item = '  File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
                   (Colors.filename, filename, Colors.Normal,
                    Colors.lineno, lineno, Colors.Normal,
                    Colors.name, name, Colors.Normal)
            if line:
                item += '    %s\n' % line.strip()
            list.append(item)
        # Emphasize the last entry
        filename, lineno, name, line = extracted_list[-1]
        item = '%s  File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
               (Colors.normalEm,
                Colors.filenameEm, filename, Colors.normalEm,
                Colors.linenoEm, lineno, Colors.normalEm,
                Colors.nameEm, name, Colors.normalEm,
                Colors.Normal)
        if line:
            item += '%s    %s%s\n' % (Colors.line, line.strip(),
                                      Colors.Normal)
        list.append(item)
        return list
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def _some_str(self, value):
        # Lifted from traceback.py
        try:
            return py3compat.cast_unicode(str(value))
        except:
            return u'<unprintable %s object>' % type(value).__name__


#----------------------------------------------------------------------------
项目:FLASH    作者:yuyuz    | 项目源码 | 文件源码
def format_traceback(exc_info):
    traceback_template = '''Traceback (most recent call last):
    File "%(filename)s", line %(lineno)s, in %(name)s
    %(type)s: %(message)s\n''' # Skipping the "actual line" item

    # Also note: we don't walk all the way through the frame stack in this example
    # see hg.python.org/cpython/file/8dffb76faacc/Lib/traceback.py#l280
    # (Imagine if the 1/0, below, were replaced by a call to test() which did 1/0.)

    exc_type, exc_value, exc_traceback = exc_info  # most recent (if any) by default

    '''
    Reason this _can_ be bad: If an (unhandled) exception happens AFTER this,
    or if we do not delete the labels on (not much) older versions of Py, the
    reference we created can linger.

    traceback.format_exc/print_exc do this very thing, BUT note this creates a
    temp scope within the function.
    '''

    traceback_details = {
                         'filename': exc_traceback.tb_frame.f_code.co_filename,
                         'lineno'  : exc_traceback.tb_lineno,
                         'name'    : exc_traceback.tb_frame.f_code.co_name,
                         'type'    : exc_type.__name__,
                         'message' : exc_value.message, # or see traceback._some_str()
                        }

    del(exc_type, exc_value, exc_traceback) # So we don't leave our local labels/objects dangling
    # This still isn't "completely safe", though!
    # "Best (recommended) practice: replace all exc_type, exc_value, exc_traceback
    # with sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]

    return "\n" + traceback.format_exc() + "\n\n" + traceback_template % traceback_details + "\n\n"
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def _fixed_getinnerframes(etb, context=1, tb_offset=0):
    LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5

    records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
    # If the error is at the console, don't build any context, since it would
    # otherwise produce 5 blank lines printed out (there is no file at the
    # console)
    rec_check = records[tb_offset:]
    try:
        rname = rec_check[0][1]
        if rname == '<ipython console>' or rname.endswith('<string>'):
            return rec_check
    except IndexError:
        pass

    aux = traceback.extract_tb(etb)
    assert len(records) == len(aux)
    for i, (file, lnum, _, _) in zip(range(len(records)), aux):
        maybeStart = lnum - 1 - context // 2
        start = max(maybeStart, 0)
        end = start + context
        lines = ulinecache.getlines(file)[start:end]
        buf = list(records[i])
        buf[LNUM_POS] = lnum
        buf[INDEX_POS] = lnum - 1 - start
        buf[LINES_POS] = lines
        records[i] = tuple(buf)
    return records[tb_offset:]

# Helper function -- largely belongs to VerboseTB, but we need the same
# functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
# can be recognized properly by ipython.el's py-traceback-line-re
# (SyntaxErrors have to be treated specially because they have no traceback)
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def _format_list(self, extracted_list):
        """Format a list of traceback entry tuples for printing.

        Given a list of tuples as returned by extract_tb() or
        extract_stack(), return a list of strings ready for printing.
        Each string in the resulting list corresponds to the item with the
        same index in the argument list.  Each string ends in a newline;
        the strings may contain internal newlines as well, for those items
        whose source text line is not None.

        Lifted almost verbatim from traceback.py
        """

        Colors = self.Colors
        list = []
        for filename, lineno, name, line in extracted_list[:-1]:
            item = '  File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
                   (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal,
                    Colors.lineno, lineno, Colors.Normal,
                    Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal)
            if line:
                item += '    %s\n' % line.strip()
            list.append(item)
        # Emphasize the last entry
        filename, lineno, name, line = extracted_list[-1]
        item = '%s  File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
               (Colors.normalEm,
                Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm,
                Colors.linenoEm, lineno, Colors.normalEm,
                Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm,
                Colors.Normal)
        if line:
            item += '%s    %s%s\n' % (Colors.line, line.strip(),
                                      Colors.Normal)
        list.append(item)
        return list
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def _some_str(self, value):
        # Lifted from traceback.py
        try:
            return py3compat.cast_unicode(str(value))
        except:
            return u'<unprintable %s object>' % type(value).__name__


#----------------------------------------------------------------------------
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def _fixed_getinnerframes(etb, context=1, tb_offset=0):
    LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5

    records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
    # If the error is at the console, don't build any context, since it would
    # otherwise produce 5 blank lines printed out (there is no file at the
    # console)
    rec_check = records[tb_offset:]
    try:
        rname = rec_check[0][1]
        if rname == '<ipython console>' or rname.endswith('<string>'):
            return rec_check
    except IndexError:
        pass

    aux = traceback.extract_tb(etb)
    assert len(records) == len(aux)
    for i, (file, lnum, _, _) in zip(range(len(records)), aux):
        maybeStart = lnum - 1 - context // 2
        start = max(maybeStart, 0)
        end = start + context
        lines = ulinecache.getlines(file)[start:end]
        buf = list(records[i])
        buf[LNUM_POS] = lnum
        buf[INDEX_POS] = lnum - 1 - start
        buf[LINES_POS] = lines
        records[i] = tuple(buf)
    return records[tb_offset:]

# Helper function -- largely belongs to VerboseTB, but we need the same
# functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
# can be recognized properly by ipython.el's py-traceback-line-re
# (SyntaxErrors have to be treated specially because they have no traceback)
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def _format_list(self, extracted_list):
        """Format a list of traceback entry tuples for printing.

        Given a list of tuples as returned by extract_tb() or
        extract_stack(), return a list of strings ready for printing.
        Each string in the resulting list corresponds to the item with the
        same index in the argument list.  Each string ends in a newline;
        the strings may contain internal newlines as well, for those items
        whose source text line is not None.

        Lifted almost verbatim from traceback.py
        """

        Colors = self.Colors
        list = []
        for filename, lineno, name, line in extracted_list[:-1]:
            item = '  File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
                   (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal,
                    Colors.lineno, lineno, Colors.Normal,
                    Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal)
            if line:
                item += '    %s\n' % line.strip()
            list.append(item)
        # Emphasize the last entry
        filename, lineno, name, line = extracted_list[-1]
        item = '%s  File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
               (Colors.normalEm,
                Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm,
                Colors.linenoEm, lineno, Colors.normalEm,
                Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm,
                Colors.Normal)
        if line:
            item += '%s    %s%s\n' % (Colors.line, line.strip(),
                                      Colors.Normal)
        list.append(item)
        return list
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def _some_str(self, value):
        # Lifted from traceback.py
        try:
            return py3compat.cast_unicode(str(value))
        except:
            return u'<unprintable %s object>' % type(value).__name__


#----------------------------------------------------------------------------
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def _fixed_getinnerframes(etb, context=1, tb_offset=0):
    LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5

    records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
    # If the error is at the console, don't build any context, since it would
    # otherwise produce 5 blank lines printed out (there is no file at the
    # console)
    rec_check = records[tb_offset:]
    try:
        rname = rec_check[0][1]
        if rname == '<ipython console>' or rname.endswith('<string>'):
            return rec_check
    except IndexError:
        pass

    aux = traceback.extract_tb(etb)
    assert len(records) == len(aux)
    for i, (file, lnum, _, _) in enumerate(aux):
        maybeStart = lnum - 1 - context // 2
        start = max(maybeStart, 0)
        end = start + context
        lines = linecache.getlines(file)[start:end]
        buf = list(records[i])
        buf[LNUM_POS] = lnum
        buf[INDEX_POS] = lnum - 1 - start
        buf[LINES_POS] = lines
        records[i] = tuple(buf)
    return records[tb_offset:]

# Helper function -- largely belongs to VerboseTB, but we need the same
# functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
# can be recognized properly by ipython.el's py-traceback-line-re
# (SyntaxErrors have to be treated specially because they have no traceback)
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def _format_list(self, extracted_list):
        """Format a list of traceback entry tuples for printing.

        Given a list of tuples as returned by extract_tb() or
        extract_stack(), return a list of strings ready for printing.
        Each string in the resulting list corresponds to the item with the
        same index in the argument list.  Each string ends in a newline;
        the strings may contain internal newlines as well, for those items
        whose source text line is not None.

        Lifted almost verbatim from traceback.py
        """

        Colors = self.Colors
        list = []
        for filename, lineno, name, line in extracted_list[:-1]:
            item = '  File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
                   (Colors.filename, filename, Colors.Normal,
                    Colors.lineno, lineno, Colors.Normal,
                    Colors.name, name, Colors.Normal)
            if line:
                item += '    %s\n' % line.strip()
            list.append(item)
        # Emphasize the last entry
        filename, lineno, name, line = extracted_list[-1]
        item = '%s  File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
               (Colors.normalEm,
                Colors.filenameEm, filename, Colors.normalEm,
                Colors.linenoEm, lineno, Colors.normalEm,
                Colors.nameEm, name, Colors.normalEm,
                Colors.Normal)
        if line:
            item += '%s    %s%s\n' % (Colors.line, line.strip(),
                                      Colors.Normal)
        list.append(item)
        return list
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def _some_str(self, value):
        # Lifted from traceback.py
        try:
            return py3compat.cast_unicode(str(value))
        except:
            return u'<unprintable %s object>' % type(value).__name__


#----------------------------------------------------------------------------