Notebook files often move from interactive exploration into scheduled reports, regression checks, or release jobs. Executing a Jupyter Notebook from the command line lets nbconvert run each cell through the notebook kernel and save a fresh .ipynb artifact with new outputs.
The --execute preprocessor runs the notebook before the notebook exporter writes the result. Writing to a separate output name keeps the original notebook unchanged, which matters when the source file is tracked in Git or used as a review copy.
The notebook must already have a working kernel specification and the project dependencies available in the shell that runs the command. By default, nbconvert stops on the first unhandled cell error, so automation jobs can treat a nonzero exit as a failed notebook run.
Steps to execute a Jupyter Notebook from the command line with nbconvert:
- Open a terminal in the directory where the notebook expects to read and write files.
nbconvert runs relative paths from the current working directory. Use the same project directory that the notebook uses in the browser or scheduler.
- Execute the notebook to a separate output file.
$ jupyter nbconvert --to notebook --execute analysis-demo.ipynb --output analysis-executed [NbConvertApp] Converting notebook analysis-demo.ipynb to notebook [NbConvertApp] Writing 1671 bytes to analysis-executed.ipynb
Replace analysis-demo.ipynb with the notebook to run. --output is the output basename, and nbconvert adds the .ipynb extension for the notebook exporter. Leave --allow-errors off when failed cells should stop the job.
- Check that the executed notebook was written.
$ ls -lh analysis-executed.ipynb -rw-r--r-- 1 user user 1.7K Jul 6 12:40 analysis-executed.ipynb
- Verify that the saved notebook contains executed code cells and output.
$ python - <<'PY' import json with open("analysis-executed.ipynb", encoding="utf-8") as f: nb = json.load(f) code_cells = [cell for cell in nb["cells"] if cell["cell_type"] == "code"] executed = sum(cell.get("execution_count") is not None for cell in code_cells) output_lines = [] for cell in code_cells: for output in cell.get("outputs", []): output_lines.extend(output.get("text", [])) print(f"executed code cells: {executed} of {len(code_cells)}") print("saved output:") for line in output_lines: print(line.strip()) PY executed code cells: 2 of 2 saved output: monthly revenue: 125000 status: complete
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.