Sub topic 12
Running notebooks from the command line
This chapter covers running a notebook from start to finish without opening Jupyter. It assumes you can use Jupyter, a shell, and a virtual environment, and that you have already used "Restart and run all" as a check. Here you automate that check and make it repeatable.
Why run a notebook headlessly
A headless run executes a notebook with no browser and no person clicking cells. It matters for reproducibility for three reasons:
- It always starts a fresh kernel, so hidden state from earlier sessions cannot leak in.
- It runs cells strictly top to bottom, so execution order cannot drift.
- It can be repeated by a script, a scheduler, or a CI job, so anyone can rerun the analysis with one command.
A notebook that only works when you run cells by hand in a certain order has not been shown to be reproducible. A notebook that finishes in a headless run has passed a much stricter test.
Executing with nbconvert
The jupyter nbconvert tool ships with Jupyter. Its --execute flag runs every cell in order in a new kernel and writes the result.
jupyter nbconvert --to notebook --execute analysis.ipynb --output analysis_executed.ipynbThis command:
- Starts a kernel using the notebook's kernel specification.
- Runs each cell from the first to the last.
- Saves a new notebook,
analysis_executed.ipynb, that contains the outputs.
If any cell raises an error, the run stops and the command exits with a non-zero status. A script or CI job can detect that status and treat the run as failed. This is the behavior you want. A silent failure would leave you with a notebook that looks finished but is not.
By default, --output writes next to the input file. Keep the executed copy separate from the source. Treat the source notebook as code and the executed copy as an output.
Useful options
| Option | Effect |
|---|---|
| `--output-dir outputs/` | Write the result into a chosen folder. |
| `--ExecutePreprocessor.timeout=600` | Allow each cell up to 600 seconds. The default is 30 seconds, and the run fails if a cell exceeds the limit. Use `-1` for no limit. |
| `--ExecutePreprocessor.kernel_name=python3` | Choose the kernel by name instead of using the one stored in the notebook. |
| `--allow-errors` | Continue after a cell fails. Avoid this for reproducibility checks, because it hides failures. |
| `--to html` | Produce an HTML report instead of a notebook. |
The timeout is a common source of confusion. A cell that trains a model or reads a large file can take longer than 30 seconds, and the run then fails with a timeout error even though the code is correct. Raise the limit on purpose, and pick a value that still catches a real hang.
Choosing the right kernel
A headless run uses the kernel named in the notebook's metadata. If that name points to a different environment than the one you activated, the notebook runs with the wrong packages. This is a frequent cause of "it works in my session but not in the script."
To avoid it, register your project environment as a named kernel, then run with that kernel.
source .venv/bin/activate
pip install ipykernel
python -m ipykernel install --user --name myproject --display-name "Python (myproject)"
jupyter nbconvert --to notebook --execute analysis.ipynb \
--ExecutePreprocessor.kernel_name=myproject \
--output analysis_executed.ipynbAfter a run, check the environment details printed by the notebook (see the chapter on recording run metadata). The Python path and package versions should match the virtual environment you meant to use.
Running with parameters using Papermill
nbconvert runs a notebook as it is. Papermill adds the ability to change inputs for a run without editing the notebook. This relies on parameterization, where you mark one cell as the place that defines default values.
In the notebook, create a cell near the top that holds the defaults, and give it the tag parameters:
alpha = 0.05
input_path = "data/raw/measurements.csv"Papermill finds the cell with that tag. It inserts a new cell right after it that holds the values you pass in. Because the injected cell comes later, its values override the defaults.
Run it from the command line:
pip install papermill
papermill analysis.ipynb outputs/analysis_alpha_0.1.ipynb -p alpha 0.1The -p option sets a parameter. You can repeat it for several parameters. The first path is the input notebook, and the second is where the executed copy goes. Papermill always writes a new file, so the source notebook stays unchanged.
Some points to keep in mind:
- Papermill passes simple values such as numbers, strings, and booleans. For something complex, pass a file path and load the object inside the notebook.
- Put the output name in the file name, as in
analysis_alpha_0.1.ipynb, so you can tell runs apart later. - Keep the parameters cell small. It should hold inputs only, not logic.
- If no cell is tagged
parameters, Papermill still injects a cell, but at the top, and it warns you. Tag the cell so the behavior is clear.
You can also pass many parameters from a YAML file with -f params.yaml, which keeps long argument lists out of your shell history and makes a run easy to record.
Exit codes and failure handling
Both tools return a non-zero exit status when a run fails. In a shell script you can rely on this:
#!/usr/bin/env bash
set -euo pipefail
source .venv/bin/activate
mkdir -p outputs
papermill analysis.ipynb outputs/analysis_alpha_0.1.ipynb -p alpha 0.1
echo "Run finished"set -e makes the script stop at the first failed command, so "Run finished" prints only if the notebook ran cleanly. set -u stops on use of an unset variable. set -o pipefail makes a pipeline fail if any step in it fails.
Papermill saves the partially executed notebook when a cell fails, and it marks the failing cell. Open that output file to see exactly where the run stopped and what the error was. This makes the executed copy useful for debugging even when the run fails.
Edge cases and common errors
- Relative paths. A headless run uses the notebook's own folder as the working directory. A path such as
data/raw/measurements.csvthen resolves from the notebook's location, not from where you typed the command. If your notebooks live innotebooks/and data lives indata/, use a path relative to the notebook or compute the project root in code. - Interactive code. Calls such as
input(), widgets that wait for a click, or plots that need a window block or fail in a headless run. Replace them with parameters and save figures to files. - Missing kernel. An error that says no such kernel exists means the kernel name in the notebook is not installed on this machine. Register the kernel or pass
kernel_name. - Cell timeouts. A "Cell execution timed out" error means a cell exceeded the limit. Raise the timeout or make the cell faster.
- Hard-coded absolute paths. A path like
/home/ana/project/data.csvworks on one machine only. Headless runs on another machine expose it, which is a useful early warning. - Different results between interactive and headless runs. This almost always means hidden state, such as a variable defined in a cell you later deleted. Fix the notebook so the headless run is correct.
Keeping run outputs organized
Write executed notebooks into an outputs/ folder and keep that folder out of the source code. Name each file after the parameters used. Do not overwrite a previous run unless you mean to. If you commit executed notebooks, remember that they carry large outputs, so many teams keep them as build artifacts instead of committing them.
Exercise
You run jupyter nbconvert --to notebook --execute analysis.ipynb and it fails with a "Cell execution timed out" error on a cell that trains a model. The code is correct when you run it by hand. What is the cause, and how do you fix it without hiding real errors?
Show answer
The default per-cell timeout is 30 seconds, and the training cell takes longer. Raise the limit with --ExecutePreprocessor.timeout=600 (or another value that suits the work). Do not use --allow-errors, because it would let genuine failures pass unnoticed.
Exercise
You use Papermill to run analysis.ipynb with -p alpha 0.1, but the executed notebook still shows alpha = 0.05 in its results. Name two things to check.
Show answer
Check that the cell holding the default alpha is tagged parameters, and that the parameter name in -p exactly matches the variable name in the notebook. Also confirm that later cells do not reassign alpha after the injected cell.