How can I open an IPython notebook without the output?

会有一股神秘感。 提交于 2019-12-04 08:05:40

问题


I have an IPython notebook where I've accidentally dumped a huge output (15 MB) that crashed the notebook. Now when I open the notebook and attempt to delete the troublesome cell, the notebook crashes again—thus preventing me from fixing the problem and restoring the notebook to stability.

The best fix I can think of is manually pasting the input cells to a new notebook, but is there a way to just open the notebook without any outputs?


回答1:


There is this nice snippet (that I use as a git commit hook) to strip the output of an ipython notebook:

#!/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")

You can easily make it a bit nicer to use, currently you'd have to call it as

strip_output.py < my_notebook.ipynb > my_notebook_stripped.ipynb



回答2:


If you are running jupyter 4.x, you will get some API deprecation warnings when running filmor's script. Although the script still works, I update the script a bit to remove the warnings.

#!/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")



回答3:


As for later versions of jupyter, there is a Restart Kernel and Clear All Outputs... option that clears the outputs but also removed the variables.



来源:https://stackoverflow.com/questions/25178118/how-can-i-open-an-ipython-notebook-without-the-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!