我有一个IPython笔记本,我不小心丢弃了一个巨大的输出(15 MB),崩溃了笔记本电脑。现在,当我打开笔记本电脑并尝试删除麻烦的电池时,笔记本电脑再次崩溃 - 从而阻止我解决问题并恢复笔记本电脑的稳定性。
我能想到的最好的解决方法是手动将输入单元格粘贴到新笔记本上,但有没有办法只打开笔记本而没有任何输出?
有一个很好的片段(我用作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
如果您运行的是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")