如何在没有输出的情况下打开IPython笔记本?

wil*_*il3 13 ipython ipython-notebook

我有一个IPython笔记本,我不小心丢弃了一个巨大的输出(15 MB),崩溃了笔记本电脑.现在,当我打开笔记本电脑并尝试删除麻烦的电池时,笔记本电脑再次崩溃 - 从而阻止我解决问题并恢复笔记本电脑的稳定性.

我能想到的最好的解决方法是手动将输入单元格粘贴到新笔记本上,但有没有办法只打开笔记本而没有任何输出?

小智 46

您可以使用 cli 清除输出

jupyter nbconvert --ClearOutputPreprocessor.enabled=True --inplace Notebook.ipynb
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案。这是我能够在配备 16GB RAM 的 M1 MB Air 上启动具有 250MB 输出的 Jupyter 笔记本的唯一方法。 (3认同)
  • 这是最简单也是最好的答案。非常有效,我和本遇到了同样的问题。 (2认同)

fil*_*mor 16

有一个很好的片段(我用作git提交钩子)来剥离ipython笔记本的输出:

#!/usr/bin/env python

def strip_output(nb):
    for ws in nb.worksheets:
        for cell in ws.cells:
            if hasattr(cell, "outputs"):
                cell.outputs = []
            if hasattr(cell, "prompt_number"):
                del cell["prompt_number"]


if __name__ == "__main__":
    from sys import stdin, stdout
    from IPython.nbformat.current import read, write

    nb = read(stdin, "ipynb")
    strip_output(nb)
    write(nb, stdout, "ipynb")
    stdout.write("\n")
Run Code Online (Sandbox Code Playgroud)

您可以轻松地使用它,目前您必须将其称为

strip_output.py < my_notebook.ipynb > my_notebook_stripped.ipynb
Run Code Online (Sandbox Code Playgroud)


Edw*_*ung 9

如果你正在运行jupyter 4.x,那么在运行filmor脚本时你会得到一些API弃用警告.虽然脚本仍然有效,但我稍微更新了脚本以删除警告.

#!/usr/bin/env python

def strip_output(nb):
    for cell in nb.cells:
        if hasattr(cell, "outputs"):
            cell.outputs = []
        if hasattr(cell, "prompt_number"):
            del cell["prompt_number"]


if __name__ == "__main__":
    from sys import stdin, stdout
    from nbformat import read, write

    nb = read(stdin, 4)
    strip_output(nb)
    write(nb, stdout, 4)
    stdout.write("\n")
Run Code Online (Sandbox Code Playgroud)


tar*_*ole 5

对于 jupyter 的更高版本,有一个Restart Kernel and Clear All Outputs...选项可以清除输出但也删除变量。

内核选项

  • OP 特别要求不需要打开笔记本的解决方案。 (2认同)