format_stack.py 文件源码

python
阅读 31 收藏 0 点赞 0 评论 0

项目:mlens 作者: flennerhag 项目源码 文件源码
def format_outer_frames(context=5, stack_start=None, stack_end=None,
                        ignore_ipython=True):
    LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
    records = inspect.getouterframes(inspect.currentframe())
    output = list()

    for i, (frame, filename, line_no, func_name, lines, index) \
                                                in enumerate(records):
        # Look inside the frame's globals dictionary for __file__, which should
        # be better.
        better_fn = frame.f_globals.get('__file__', None)
        if isinstance(better_fn, str):
            # Check the type just in case someone did something weird with
            # __file__. It might also be None if the error occurred during
            # import.
            filename = better_fn
            if filename.endswith('.pyc'):
                filename = filename[:-4] + '.py'
        if ignore_ipython:
            # Hack to avoid printing the internals of IPython
            if (os.path.basename(filename) in ('iplib.py', 'py3compat.py')
                        and func_name in ('execfile', 'safe_execfile', 'runcode')):
                break
        maybe_start = line_no - 1 - context // 2
        start = max(maybe_start, 0)
        end = start + context
        lines = linecache.getlines(filename)[start:end]
        buf = list(records[i])
        buf[LNUM_POS] = line_no
        buf[INDEX_POS] = line_no - 1 - start
        buf[LINES_POS] = lines
        output.append(tuple(buf))
    return '\n'.join(format_records(output[stack_end:stack_start:-1]))
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号