簡體   English   中英

如何同時捕獲和顯示 ipython (jupyter notebook) 單元格輸出?

[英]How to simultaneously capture and display ipython (jupyter notebook) cell output?

您如何在jupyter notebook捕獲單元格輸出,同時顯示結果? 我不想等待一切都完成然后運行一個 variable.show()。

在此處輸入圖片說明

我從內置%%capture實現中改編了以下自定義單元格魔法:

from io import StringIO
import sys

from IPython.core import magic_arguments
from IPython.core.magic import Magics, cell_magic, magics_class
from IPython.utils.capture import CapturedIO


class Tee(StringIO):
    def __init__(self, initial_value='', newline='\n', stream=None):
        self.stream = stream
        super().__init__(initial_value, newline)
    
    def write(self, data):
        if self.stream is not None:
            self.stream.write(data)
        
        super().write(data)


class capture_and_print_output(object):
    stdout = True
    stderr = True
    display = True
    
    def __init__(self, stdout=True, stderr=True, display=True):
        self.stdout = stdout
        self.stderr = stderr
        self.display = display
        self.shell = None
    
    def __enter__(self):
        from IPython.core.getipython import get_ipython
        from IPython.core.displaypub import CapturingDisplayPublisher
        from IPython.core.displayhook import CapturingDisplayHook
        
        self.sys_stdout = sys.stdout
        self.sys_stderr = sys.stderr
        
        if self.display:
            self.shell = get_ipython()
            if self.shell is None:
                self.save_display_pub = None
                self.display = False
        
        stdout = stderr = outputs = None
        if self.stdout:
            stdout = sys.stdout = Tee(stream=sys.stdout)
        if self.stderr:
            stderr = sys.stderr = Tee(stream=sys.stderr)
        if self.display:
            self.save_display_pub = self.shell.display_pub
            self.shell.display_pub = CapturingDisplayPublisher()
            outputs = self.shell.display_pub.outputs
            self.save_display_hook = sys.displayhook
            sys.displayhook = CapturingDisplayHook(shell=self.shell,
                                                   outputs=outputs)
        
        return CapturedIO(stdout, stderr, outputs)
    
    def __exit__(self, exc_type, exc_value, traceback):
        sys.stdout = self.sys_stdout
        sys.stderr = self.sys_stderr
        if self.display and self.shell:
            self.shell.display_pub = self.save_display_pub
            sys.displayhook = self.save_display_hook


@magics_class
class CustomMagics(Magics):
    @magic_arguments.magic_arguments()
    @magic_arguments.argument('output', type=str, default='', nargs='?')
    @magic_arguments.argument('--no-stderr', action='store_true')
    @magic_arguments.argument('--no-stdout', action='store_true')
    @magic_arguments.argument('--no-display', action='store_true')
    @cell_magic
    def tee(self, line, cell):
        args = magic_arguments.parse_argstring(self.tee, line)
        out = not args.no_stdout
        err = not args.no_stderr
        disp = not args.no_display
        with capture_and_print_output(out, err, disp) as io:
            self.shell.run_cell(cell)
        if args.output:
            self.shell.user_ns[args.output] = io

您需要注冊這個單元魔法,通常在您的啟動配置文件中或通過將其定義為您稍后加載的擴展,例如:

from IPython import get_ipython

get_ipython().register_magics(CustomMagics)

現在您可以按如下方式使用它:

>>> %%tee output
    print(42)
42
>>> output.show()
42

需要注意的一件事:它將像原始%%capture一樣捕獲豐富的輸出,但不會在原始單元格中打印它們。 如果這很重要,您可能會找到一些方法來調整上述內容以包含豐富的輸出,也許是通過子類化CapturingDisplayPublisher/Hook

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM