繁体   English   中英

从 nbconvert.preprocessors.ExecutePreprocessor 获取部分 output

[英]Get partial output from nbconvert.preprocessors.ExecutePreprocessor

有没有办法从 nbconvert.preprocessors.ExecutePreprocessor 获取部分 output? 目前,我使用 ExecutePreprocessor 以编程方式执行我的 Jupyter notebook,它在执行整个 notebook 后返回 output。 但是,如果能够在运行笔记本时获取并保存部分结果,那就太好了。 例如,如果我在 jupyter 笔记本中有一个进度条,有没有办法不断读取更新的执行 output 以便我可以看到它更新?

这是我当前的代码:

import nbformat
from nbconvert.preprocessors import ExecutePreprocessor

with open('./test2.ipynb') as f:
    nb = nbformat.read(f, as_version=4)
    ep = ExecutePreprocessor(timeout=600, kernel_name='python3')
    ep.preprocess(nb)
    print(nb)
    with open('executed_notebook.ipynb', 'w', encoding='utf-8') as f:
        nbformat.write(nb, f)

然而,能够在执行时连续读取 nb 变量并将其写入文件会很棒

我最终做了这样的事情

import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
import threading

f = open('./test2.ipynb')
nb = nbformat.read(f, as_version=4)
ep = ExecutePreprocessor(kernel_name='python3')
def save_notebook():
    threading.Timer(1.0, save_notebook).start()
    with open('executed_notebook.ipynb', 'w', encoding='utf-8') as f:
        nbformat.write(nb, f)
save_notebook()

ep.preprocess(nb)

print('ended')

似乎工作得很好。 如果有人有更好的解决方案,请随时发布

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM