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

问题描述 投票:13回答:3

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

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

ipython ipython-notebook
3个回答
15
投票

有一个很好的片段(我用作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")

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

strip_output.py < my_notebook.ipynb > my_notebook_stripped.ipynb

8
投票

如果您运行的是jupyter 4.x,则在运行filmor's script时会收到一些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")

2
投票

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

Kernel Options

© www.soinside.com 2019 - 2024. All rights reserved.