Skip to content

Instantly share code, notes, and snippets.

@parente
Last active December 26, 2023 14:31
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parente/bfd7548ee08b6e377da85f8e4f88d6b8 to your computer and use it in GitHub Desktop.
Save parente/bfd7548ee08b6e377da85f8e4f88d6b8 to your computer and use it in GitHub Desktop.
Jupyter Tidbit: Use nbconvert to clear notebook outputs

Summary

nbconvert has a preprocessor that clears cell outputs from notebook files, leaving cell inputs intact.

Example

The following shell command reads my_input_notebook.ipynb, removes its cell outputs, prints the cleaned notebook to stdout, and redirects that output to a new notebook file named my_output_notebook.ipynb.

jupyter nbconvert my_input_notebook.ipynb --to notebook --ClearOutputPreprocessor.enabled=True --stdout > my_output_notebook.ipynb

The following command works similiarly, but without using a redirect.

jupyter nbconvert my_input_notebook.ipynb --to notebook --ClearOutputPreprocessor.enabled=True --output my_output_notebook

Why is this useful?

One day, you may run a notebook, walk away, and return later to find your notebook has produced so much output that it has brought your browser to its knees ... after autosaving. You'll try to reload that notebook to see what went wrong, only to find that your browser tab slows to a crawl and crashes once again. Clearing outputs at the command line is one way to get out of this sticky situation.

On a lighter note, you may just want to quickly purge your notebook of output before sharing it, without having to open it in Jupyter Notebook, JupyterLab, etc.

@shreve
Copy link

shreve commented Jul 8, 2022

Hey, I just stumbled on your blog post. I wanted to let you know there's now an --inplace flag.

jupyter nbconvert --ClearOutputPreprocessor.enabled=True --inplace my_notebook.ipynb

Apparently there's also a --clear-output convenience flag, but it's broken in some current versions (jupyter/nbconvert#822).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment