python类format_list()的实例源码

humanize.py 文件源码 项目:easypy 作者: weka-io 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def format_thread_stack(frame, skip_modules=[threading]):
    stack = traceback.extract_stack(frame)
    if skip_modules:
        itr_stack = iter(stack)
        items = []
        fnames = {m.__file__ for m in ilistify(skip_modules)}
        # skip everything until after specified module
        for fname, *_ in itr_stack:
            if fname in fnames:
                items.append([fname] + _)
                for i, (fname, *_) in enumerate(itr_stack, 1):
                    if fname not in fnames:
                        if i > 1:
                            items.append([last_fname, "...(%s)" % i, "---", "---"])
                        break
                    last_fname = fname
            items.append([fname] + _)
        if len(items) <= 2:
            items = stack
    else:
        items = stack

    return ''.join(traceback.format_list(items))
code.py 文件源码 项目:Docker-XX-Net 作者: kuanghy 项目源码 文件源码 阅读 23 收藏 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)
ThreadedAppServer.py 文件源码 项目:w4py 作者: Cito 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def threadDump(signum, frame):
    """Signal handler for dumping thread stack frames to stdout."""
    print
    print "App server has been signaled to attempt a thread dump."
    print
    print "Thread stack frame dump at", asclocaltime()
    sys.stdout.flush()
    frames = sys._current_frames()
    print
    print "-" * 79
    print
    for threadID in sorted(frames):
        frame = frames[threadID]
        print "Thread ID: %d (reference count = %d)" % (
            threadID, sys.getrefcount(frame))
        print ''.join(traceback.format_list(traceback.extract_stack(frame)))
    print "-" * 79
    sys.stdout.flush()
visualstudio_py_debugger.py 文件源码 项目:DjangoWebProject 作者: wrkettlitz 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def print_exception(exc_type, exc_value, exc_tb):
    # remove debugger frames from the top and bottom of the traceback
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG):
                break
            del tb[i]

    # print the traceback
    if tb:
        print('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)

    # print the exception
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stdout.write(out)
visualstudio_py_debugger.py 文件源码 项目:ApiRestPythonTest 作者: rvfvazquez 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def print_exception(exc_type, exc_value, exc_tb):
    # remove debugger frames from the top and bottom of the traceback
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG):
                break
            del tb[i]

    # print the traceback
    if tb:
        print('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)

    # print the exception
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stdout.write(out)
code.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 27 收藏 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)
parse_trace.py 文件源码 项目:git-stacktrace 作者: pinterest 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def format_lines(self):
        lines = self.traceback_format()
        return ''.join(traceback.format_list(lines))
exceptions.py 文件源码 项目:ave 作者: sonyxperiadev 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def format_trace(self):
        if self.has_trace():
            # convert trace entries back to tuples. the trace member was
            # set by the server side rpc mechanism. rpc messages cannot
            # contain tuples (incompatible with JSON) so the entries were
            # converted to lists.
            convert = []
            for entry in self.trace:
                convert.append(tuple(entry))
            formatted = traceback.format_list(convert)
            return ''.join(formatted)
        return ''
exceptions.py 文件源码 项目:ave 作者: sonyxperiadev 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def format_trace(self):
        if self.has_trace():
            # convert trace entries back to tuples. the trace member was
            # set by the server side rpc mechanism. rpc messages cannot
            # contain tuples (incompatible with JSON) so the entries were
            # converted to lists.
            convert = []
            for entry in self.trace:
                convert.append(tuple(entry))
            formatted = traceback.format_list(convert)
            return ''.join(formatted)
        return ''
config.py 文件源码 项目:abusehelper 作者: Exploit-install 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def follow_config(path, poll_interval=1.0, force_interval=30.0):
    last_reload = -float("inf")
    last_mtime = None
    last_error_msg = None

    abspath = os.path.abspath(path)
    while True:
        now = time.time()
        if now < last_reload:
            last_reload = now

        mtime = os.path.getmtime(abspath)
        if now > last_reload + force_interval or last_mtime != mtime:
            try:
                configs = load_configs(abspath)
            except Exception:
                _, exc_value, exc_tb = sys.exc_info()

                stack = traceback.extract_tb(exc_tb)
                stack = stack[1:]  # Make the traceback flatter by discarding the current stack frame

                error_msg = "Could not load {path!r} (most recent call last):\n{stack}\n{exception}".format(
                    path=abspath,
                    stack="".join(traceback.format_list(stack)).rstrip(),
                    exception=utils.format_exception(exc_value)
                )

                if error_msg != last_error_msg:
                    yield idiokit.send(False, error_msg)
                    last_error_msg = error_msg
                    last_mtime = None
            else:
                yield idiokit.send(True, configs)
                last_error_msg = None
                last_mtime = mtime
                last_reload = now
        yield idiokit.sleep(poll_interval)
utils.py 文件源码 项目:bothub-sdk-python 作者: bothub-studio 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def traceback_to_string(exc, tb=None):
    _tb = tb or exc.__traceback__
    s = traceback.extract_stack()[:-3] + traceback.extract_tb(_tb)
    l = traceback.format_list(s)
    return ''.join(l) + '\\n  {} {}'.format(exc.__class__, exc)
debug.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def format_exception(self):
        """
        Return the same data as from traceback.format_exception.
        """
        import traceback
        frames = self.get_traceback_frames()
        tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames]
        list = ['Traceback (most recent call last):\n']
        list += traceback.format_list(tb)
        list += traceback.format_exception_only(self.exc_type, self.exc_value)
        return list
pywidgets.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def console(self, message):
        self.set_point(self.get_length())
        self.freeze()
        previous_kind = None
        style = self.get_style()
        style_cache = {}
        try:
            for element in message:
                if element[0] == 'exception':
                    s = traceback.format_list(element[1]['traceback'])
                    s.extend(element[1]['exception'])
                    s = string.join(s, '')
                else:
                    s = element[1]

                if element[0] != previous_kind:
                    style = style_cache.get(element[0], None)
                    if style is None:
                        gtk.rc_parse_string(
                            'widget \"Manhole.*.Console\" '
                            'style \"Console_%s\"\n'
                            % (element[0]))
                        self.set_rc_style()
                        style_cache[element[0]] = style = self.get_style()
                # XXX: You'd think we'd use style.bg instead of 'None'
                # here, but that doesn't seem to match the color of
                # the backdrop.
                self.insert(style.font, style.fg[gtk.STATE_NORMAL],
                            None, s)
                previous_kind = element[0]
            l = self.get_length()
            diff = self.maxBufSz - l
            if diff < 0:
                diff = - diff
                self.delete_text(0,diff)
        finally:
            self.thaw()
        a = self.get_vadjustment()
        a.set_value(a.upper - a.page_size)
visualstudio_py_launcher_nodebug.py 文件源码 项目:pythonVSCode 作者: DonJayamanne 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def handle_exception(exc_type, exc_value, exc_tb):
    # Specifies list of files not to display in stack trace.
    do_not_debug = [__file__, _vspu.__file__]
    if sys.version_info >= (3, 3):
        do_not_debug.append('<frozen importlib._bootstrap>')
    if sys.version_info >= (3, 5):
        do_not_debug.append('<frozen importlib._bootstrap_external>')

    # Remove debugger frames from the top and bottom of the traceback.
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in do_not_debug):
                break
            del tb[i]

    # Print the traceback.
    if tb:
        sys.stderr.write('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)
            sys.stderr.flush()

    # Print the exception.
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stderr.write(out)
        sys.stderr.flush()
YoutubeDL.py 文件源码 项目:Qyoutube-dl 作者: lzambella 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def trouble(self, message=None, tb=None):
        """Determine action to take when a download problem appears.

        Depending on if the downloader has been configured to ignore
        download errors or not, this method may throw an exception or
        not when errors are found, after printing the message.

        tb, if given, is additional traceback information.
        """
        if message is not None:
            self.to_stderr(message)
        if self.params.get('verbose'):
            if tb is None:
                if sys.exc_info()[0]:  # if .trouble has been called from an except block
                    tb = ''
                    if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
                        tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
                    tb += encode_compat_str(traceback.format_exc())
                else:
                    tb_data = traceback.format_list(traceback.extract_stack())
                    tb = ''.join(tb_data)
            self.to_stderr(tb)
        if not self.params.get('ignoreerrors', False):
            if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
                exc_info = sys.exc_info()[1].exc_info
            else:
                exc_info = sys.exc_info()
            raise DownloadError(message, exc_info)
        self._download_retcode = 1
exceptions.py 文件源码 项目:watchmen 作者: lycclsltt 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get_trace(self):
        '''This returns an abbreviated stack trace with lines that only concern
        the caller. In other words, the stack trace inside the Pexpect module
        is not included. '''

        tblist = traceback.extract_tb(sys.exc_info()[2])
        tblist = [item for item in tblist if ('pexpect/__init__' not in item[0])
                                           and ('pexpect/expect' not in item[0])]
        tblist = traceback.format_list(tblist)
        return ''.join(tblist)
queryset_storage.py 文件源码 项目:django-eraserhead 作者: dizballanze 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _print_traceback(self):
        base_path = getattr(settings, 'ERASERHEAD_TRACEBACK_BASE_PATH', None)
        for trace_line in traceback.format_list(self._traceback):
            if base_path and (base_path not in trace_line):
                continue
            print("\t" + trace_line.strip().replace('\n', '\n\t'))
ui.py 文件源码 项目:pytest-ui 作者: martinsmid 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def set_test_result(self, test_id, result_state, output, when, outcome,
                        exc_type=None, exc_value=None, extracted_traceback=None, last_failed_exempt=None):
        if not test_id in self.test_data:
            self.test_data[test_id] = {
                'id': test_id
            }

        if extracted_traceback:
            output += ''.join(
                traceback.format_list(extracted_traceback) +
                [exc_value]
            )

        test_data = self.test_data[test_id]
        test_data['exc_type'] = exc_type
        test_data['exc_value'] = exc_value
        test_data['exc_tb'] = extracted_traceback
        if when == 'call' and last_failed_exempt is not None:
            test_data['last_failed_exempt'] = last_failed_exempt

        # Ignore success, except for the 'call' step
        # ignore successive failure, take only the first
        if (outcome != 'passed' or when == 'call') \
            and not test_data.get('result_state'):
            test_data['result_state'] = result_state
            test_data['output'] = output
            self.ui.update_test_result(test_data)

        if when == 'teardown':
            test_data['runstate'] = None
            self.ui.update_test_line(test_data)
dataScryer.py 文件源码 项目:dataScryer 作者: Griesbacher 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def warn(*args, **kwargs):
    tb = traceback.extract_stack()
    _old_warn(*args, **kwargs)
    print("".join(traceback.format_list(tb)[:-1]))
YoutubeDL.py 文件源码 项目:youtube_downloader 作者: aksinghdce 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def trouble(self, message=None, tb=None):
        """Determine action to take when a download problem appears.

        Depending on if the downloader has been configured to ignore
        download errors or not, this method may throw an exception or
        not when errors are found, after printing the message.

        tb, if given, is additional traceback information.
        """
        if message is not None:
            self.to_stderr(message)
        if self.params.get('verbose'):
            if tb is None:
                if sys.exc_info()[0]:  # if .trouble has been called from an except block
                    tb = ''
                    if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
                        tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
                    tb += encode_compat_str(traceback.format_exc())
                else:
                    tb_data = traceback.format_list(traceback.extract_stack())
                    tb = ''.join(tb_data)
            self.to_stderr(tb)
        if not self.params.get('ignoreerrors', False):
            if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
                exc_info = sys.exc_info()[1].exc_info
            else:
                exc_info = sys.exc_info()
            raise DownloadError(message, exc_info)
        self._download_retcode = 1


问题


面经


文章

微信
公众号

扫码关注公众号