Jupyter笔记本同时显示和捕获输出

16

我正在尝试找到一种方法来“保存”jupyter笔记本中的变量,同时捕获丰富的输出。主要是为了避免ssh断开连接等原因。仅仅赋值给变量是不起作用的,因为一些库会打印信息,例如进度条。

目前最有希望的方法是使用%%capture,但是似乎在最近的版本中,它只捕获输出而不在浏览器会话处输出。理想情况下,我正在寻找既可以在浏览器会话处输出输出,又可以在被中断时稍后转储被捕获的输出的解决方案。


你能否发布一个示例代码,展示你目前是如何实现这个功能的? - WMRamadan
文档建议使用%%capture命令时可以选择性地指定一个变量来保存输出结果,该变量可以调用.show()方法来显示所捕获的内容。 - Mars Buttfield-Addison
我用jupyter-lab检查了一下,确实没有输出,但也许我们可以使用一些cell magic。 - David Davó
1个回答

1
我们可以使用register_cell_magic创建自定义魔法,基于IPython的capture代码,我可以编写这个函数来模拟Linux的tee命令(因此命名为Tee)。我所做的唯一事情就是将其从类中提取出来,并在结尾处调用io
from IPython import get_ipython
from IPython.core import magic_arguments
from IPython.core.magic import register_cell_magic
from IPython.utils.capture import capture_output

@magic_arguments.magic_arguments()
@magic_arguments.argument('output', type=str, default='', nargs='?',
    help="""The name of the variable in which to store output.
    This is a utils.io.CapturedIO object with stdout/err attributes
    for the text of the captured output.
    CapturedOutput also has a show() method for displaying the output,
    and __call__ as well, so you can use that to quickly display the
    output.
    If unspecified, captured output is discarded.
    """
)
@magic_arguments.argument('--no-stderr', action="store_true",
    help="""Don't capture stderr."""
)
@magic_arguments.argument('--no-stdout', action="store_true",
    help="""Don't capture stdout."""
)
@magic_arguments.argument('--no-display', action="store_true",
    help="""Don't capture IPython's rich display."""
)
@register_cell_magic
def tee(line, cell):
    args = magic_arguments.parse_argstring(tee, line)
    out = not args.no_stdout
    err = not args.no_stderr
    disp = not args.no_display
    with capture_output(out, err, disp) as io:
        get_ipython().run_cell(cell)
    if args.output:
        get_ipython().user_ns[args.output] = io
    
    io()

如下图所示,它正在正常工作。 Jupyter notebook 截图

这只会在计算完成后打印单元格的输出。我希望能够在单元格运行时看到进度,并在之后保存进度。 - Tim Kuipers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接