Notebook work often starts as exploratory cells, but code reviews, schedulers, and source-control diffs usually need a plain Python file. nbconvert can export a Python notebook into a .py script so the same code can move out of the browser-based notebook interface.
The Python exporter writes code cells, markdown cells as comments, and notebook cell markers into a script with the same base name as the notebook. Treat the generated file as a handoff artifact before committing or scheduling it, because cell order, hidden notebook state, and notebook-only syntax can change how it behaves outside Jupyter.
Use the Python export when the next step is editing, reviewing, or running notebook code as a script. If the narrative text, saved output, or rendered charts matter more than executable code, export the notebook to Markdown or HTML instead.
Steps to convert a Jupyter Notebook to a Python script with nbconvert:
- Save the notebook after arranging the cells that should become script code.
nbconvert reads the saved .ipynb file. It does not execute cells before exporting unless --execute is added.
Related: How to execute a Jupyter Notebook from the command line - Convert the notebook with the Python exporter.
$ jupyter nbconvert --to python analysis-demo.ipynb [NbConvertApp] Converting notebook analysis-demo.ipynb to python [NbConvertApp] Writing 209 bytes to analysis-demo.py
Replace analysis-demo.ipynb with the notebook to export. The generated script keeps the same base name and uses .py.
- Check that the Python script was written.
$ ls -lh analysis-demo.py -rw-r--r-- 1 user user 209 Jul 6 12:35 analysis-demo.py
- Review the generated script before using it outside Jupyter.
- analysis-demo.py
#!/usr/bin/env python # coding: utf-8 # # Analysis script demo # # Prepare notebook code for script review. # In[ ]: rows = [2, 4, 6] print(f'Total rows: {len(rows)}') print(f'Total value: {sum(rows)}')
- Compile the generated script to check Python syntax.
$ python -m py_compile analysis-demo.py
No output means Python parsed the generated script without a syntax error.
- Run the generated script in the same environment used by the notebook.
$ python analysis-demo.py Total rows: 3 Total value: 12
Notebook cells that use IPython magics, shell escapes, widgets, display hooks, or hidden session state may need edits before the generated file runs as a normal Python script.
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.