gen_rst.py 文件源码

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

项目:tensorly 作者: tensorly 项目源码 文件源码
def execute_code_block(src_file, code_block, lineno, example_globals,
                       block_vars, gallery_conf):
    """Executes the code block of the example file"""
    time_elapsed = 0

    # If example is not suitable to run, skip executing its blocks
    if not block_vars['execute_script']:
        return '', time_elapsed

    plt.close('all')
    cwd = os.getcwd()
    # Redirect output to stdout and
    orig_stdout = sys.stdout
    src_file = block_vars['src_file']

    # First cd in the original example dir, so that any file
    # created by the example get created in this directory
    my_stdout = MixedEncodingStringIO()
    os.chdir(os.path.dirname(src_file))
    sys.stdout = my_stdout

    try:
        code_ast = ast.parse(code_block, src_file)
        ast.increment_lineno(code_ast, lineno - 1)
        t_start = time()
        # don't use unicode_literals at the top of this file or you get
        # nasty errors here on Py2.7
        exec(compile(code_ast, src_file, 'exec'), example_globals)
        time_elapsed = time() - t_start

    except Exception:
        sys.stdout = orig_stdout
        except_rst = handle_exception(sys.exc_info(), src_file, block_vars,
                                      gallery_conf)
        code_output = u"\n{0}\n\n\n\n".format(except_rst)

    else:
        sys.stdout = orig_stdout
        os.chdir(cwd)

        my_stdout = my_stdout.getvalue().strip().expandtabs()
        if my_stdout:
            stdout = CODE_OUTPUT.format(indent(my_stdout, u' ' * 4))
            logger.verbose('Output from %s', src_file, color='brown')
            logger.verbose(my_stdout)
        else:
            stdout = ''
        images_rst, fig_num = save_figures(block_vars['image_path'],
                                           block_vars['fig_count'],
                                           gallery_conf)

        block_vars['fig_count'] += fig_num
        code_output = u"\n{0}\n\n{1}\n\n".format(images_rst, stdout)

    finally:
        os.chdir(cwd)
        sys.stdout = orig_stdout

    return code_output, time_elapsed
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号