Sub topic 13
Export and run notebooks with nbconvert
This chapter assumes you have a working project environment with JupyterLab, pandas, and matplotlib. It also assumes a registered kernel such as data-analysis, and a notebook like analysis.ipynb that loads data/sales.csv. You should be comfortable running commands in a terminal with the virtual environment active.
What nbconvert does
nbconvert is a command-line tool and Python library that converts a notebook file (.ipynb, which is JSON) into other formats. It can also run the notebook first. It is installed as a dependency of JupyterLab, so you already have it. Check with:
jupyter nbconvert --versionnbconvert does two separate jobs, and keeping them apart avoids most confusion:
- Converting takes the notebook as it is, including saved outputs, and writes it in another format.
- Executing starts a kernel, runs every cell in order, and stores the new outputs in the notebook before any conversion happens.
Export to a static report
The simplest case is an HTML export, from the command in the Topic Spine:
jupyter nbconvert --to html analysis.ipynbThis writes analysis.html next to the notebook. The file contains your code, text, and outputs, including plots embedded as images. You can send it to someone who has no Python installed.
Because this command does not execute anything, the report shows whatever outputs were saved in the notebook the last time you ran it. If you edited a cell and did not rerun it, the report is stale. To avoid that, execute during export:
jupyter nbconvert --to html --execute analysis.ipynbControl where the file goes
Use --output for the file name (without the extension) and --output-dir for the folder:
jupyter nbconvert --to html --output sales-report --output-dir reports analysis.ipynbThis creates reports/sales-report.html. The folder is created if it does not exist.
Hide code for non-technical readers
Managers often want results, not code. Hide the input cells with:
jupyter nbconvert --to html --no-input analysis.ipynb--no-input removes code cells' source but keeps their outputs and your Markdown text. Older nbconvert versions (before 6) use --TemplateExporter.exclude_input=True instead. Hiding the code in the report does not remove it from the .ipynb file, so do not rely on this for secrets.
Other output formats
The --to option selects the exporter.
| Format | `--to` value | Notes |
|---|---|---|
| HTML | `html` | Self-contained apart from fonts and scripts loaded from the web. |
| PDF via LaTeX | `pdf` | Requires pandoc and a LaTeX distribution. |
| PDF via browser | `webpdf` | Requires `pip install "nbconvert[webpdf]"` and a Chromium download through Playwright. |
| Markdown | `markdown` | Writes a `.md` file and a `analysis_files/` folder for images. |
| Python script | `script` | Writes `analysis.py`, with Markdown cells as comments. |
| Slides | `slides` | Reveal.js presentation, driven by slide types set per cell. |
| Notebook | `notebook` | Notebook to notebook, used with `--execute` or output clearing. |
PDF is where most export errors come from. The pdf exporter fails with a message about xelatex or pandoc not found if those programs are missing, and they are not Python packages, so pip cannot install them. If you do not want a LaTeX install, webpdf is usually the easier route:
python -m pip install "nbconvert[webpdf]"
python -m playwright install chromium
jupyter nbconvert --to webpdf analysis.ipynbScript export and magics
Exporting to a script is handy for turning a finished analysis into a scheduled job:
jupyter nbconvert --to script analysis.ipynbMagic commands such as %matplotlib inline are not valid Python outside IPython. nbconvert rewrites them as calls like get_ipython().run_line_magic('matplotlib', 'inline'). The script then only runs under IPython, or it raises NameError: name 'get_ipython' is not defined under plain python. Either run it with ipython analysis.py, or remove the magics from the notebook before exporting.
Run a notebook from the command line
The second command from the Topic Spine re-runs every cell in order and saves the new outputs in the same file:
jupyter nbconvert --to notebook --execute --inplace analysis.ipynbEach flag has a specific effect:
--to notebookkeeps the output format as.ipynb.--executeruns all cells from top to bottom in a fresh kernel.--inplaceoverwrites the input file. Without it, nbconvert writesanalysis.nbconvert.ipynb, which is safer while you experiment.
A fresh kernel running top to bottom is exactly the "restart and run all" check from the hidden-state chapter. Running it from the command line makes that check automatic. If the notebook only works because of a cell you ran out of order, this command exposes it.
Choose the right kernel
nbconvert uses the kernel recorded in the notebook's metadata. If that name does not exist on the current machine, you get NoSuchKernel. List what is installed, then override if needed:
jupyter kernelspec list
jupyter nbconvert --to notebook --execute --ExecutePreprocessor.kernel_name=data-analysis analysis.ipynbRun nbconvert from the same activated virtual environment that holds your packages. If jupyter resolves to a different Python than the kernel's, you may see ModuleNotFoundError: No module named 'pandas' during execution even though pandas is installed elsewhere.
Handle failures and slow cells
By default, execution stops at the first cell that raises an exception, and nbconvert exits with a non-zero status. It prints a CellExecutionError that shows the failing cell and traceback. That is the behavior you want in scripts and automation.
Two options change this:
--allow-errorscontinues past errors and stores the tracebacks as outputs. This is useful for producing a report that shows where something broke, but it hides failures from automation, so avoid it in pipelines.--ExecutePreprocessor.timeout=600sets how many seconds a single cell may run. The default is 30 seconds in older versions andNonein some newer configurations, so set it explicitly for long cells. A cell that exceeds it raisesCellTimeoutError.
Working directory
The kernel starts in the notebook's directory, so a relative path like data/sales.csv resolves from there, not from where you typed the command. If your notebook is in a subfolder and your data folder is at the project root, the path must account for that. Otherwise you get FileNotFoundError only in automated runs.
Use the Python API
When you need to run several notebooks or choose settings in code, use nbconvert's library interface:
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
nb = nbformat.read("analysis.ipynb", as_version=4)
runner = ExecutePreprocessor(timeout=600, kernel_name="data-analysis")
runner.preprocess(nb, {"metadata": {"path": "."}})
nbformat.write(nb, "analysis-executed.ipynb")The path entry sets the directory the kernel starts in. This writes to a new file, so the original stays untouched.
Pass settings into a run
nbconvert has no built-in way to pass parameters into a notebook. Two simple patterns work without extra tools:
- Read an environment variable in the first code cell, with a default:
```python import os
INPUTPATH = os.environ.get("SALESCSV", "data/sales.csv") ```
- Set it when you launch the run, for example
SALES_CSV=data/sales_2026.csv jupyter nbconvert --to html --execute analysis.ipynbon macOS or Linux.
For heavier parameterization, a separate tool such as Papermill is the usual choice. It is outside this tutorial's scope.
Clear outputs before sharing or committing
nbconvert can also strip outputs, which complements the nbstripout filter used for Git:
jupyter nbconvert --to notebook --ClearOutputPreprocessor.enabled=True --output clean analysis.ipynbThis writes clean.ipynb with all outputs removed and leaves the original alone.
Common mistakes
- Sharing stale HTML. Exporting without
--executepublishes old outputs. Add--executefor any report others will rely on. - Using
--inplacewith--to html.--inplaceonly applies to notebook output. Execute and export in one command instead. - Wrong environment. Running
jupyter nbconvertfrom a shell where the virtual environment is not active uses a different Python. - Treating
--no-inputas redaction. The code is hidden in the report only. Anyone with the.ipynbcan read it.
Exercise
Your teammate's CI job runs jupyter nbconvert --to html --execute --allow-errors analysis.ipynb and reports success, but the HTML report has a traceback in the middle. What is the cause, and what change makes the job fail correctly?
Show answer
--allow-errors tells nbconvert to continue after a cell raises an exception and to store the traceback as output, so the command exits with status 0. Remove --allow-errors. Then nbconvert stops at the first failing cell, prints a CellExecutionError, and exits with a non-zero status that CI treats as a failure.
Exercise
Write one command that re-runs analysis.ipynb with the data-analysis kernel, allows each cell up to 5 minutes, and writes a code-free HTML report named summary.html into a reports folder.
Show answer
jupyter nbconvert --to html --execute --no-input --ExecutePreprocessor.kernel_name=data-analysis --ExecutePreprocessor.timeout=300 --output summary --output-dir reports analysis.ipynb