Jupyter Notebook to Python Script Converter
Convert .ipynb notebooks to clean .py scripts with nbconvert, jupytext, and papermill — with CI/CD integration and best practices.
Why Convert Notebooks to Scripts?
Jupyter notebooks are indispensable for exploratory data analysis and rapid prototyping, but they come with real friction in production workflows. Version control diffs are noisy JSON blobs, notebooks can't be imported as modules, and CI/CD pipelines expect plain Python files. Converting .ipynb files to .py scripts unlocks cleaner Git history, standard linting tools, automated testing with pytest, and straightforward deployment to production systems.
The Python ecosystem offers three distinct tools for this — each solving a different part of the problem. nbconvert is the standard one-way exporter. Jupytext maintains bidirectional sync between notebook and script formats. Papermill executes parameterized notebooks without converting them at all. Understanding which tool fits your workflow is the first step.
nbconvert: The Standard CLI Converter
nbconvert ships with JupyterLab and is the go-to tool for one-time or scripted conversions. It supports multiple output formats including Python scripts, HTML, LaTeX, PDF, Markdown, and RST. For script conversion, markdown cells become Python comments and code cells are preserved as-is.
# Basic conversion
jupyter nbconvert --to script analysis.ipynb
# Convert all notebooks in a directory
jupyter nbconvert --to script notebooks/*.ipynb
# Convert and execute before exporting
jupyter nbconvert --to script --execute analysis.ipynb
# Strip outputs first, then convert
pip install nbstripout
nbstripout analysis.ipynb
jupyter nbconvert --to script analysis.ipynb
# Export only code (no markdown as comments)
jupyter nbconvert --to script --no-prompt analysis.ipynb Key flags to know:
--to script— output format (also: html, pdf, markdown, rst)--execute— run the notebook before exporting--output-dir— specify a different output directory--no-prompt— omit In[N] / Out[N] prompts--TagRemovePreprocessor.enabled=True— filter cells by tag
Papermill: Parameterized Notebook Execution
Papermill takes a different approach — instead of converting notebooks to scripts, it runs them with injected parameters and saves the executed output as a new notebook. This is ideal for scheduled reports, batch processing jobs, and model retraining pipelines where you want to preserve the rich output (plots, DataFrames, logs) alongside the code.
Tag a cell with parameters in Jupyter's cell metadata to mark it as the injection point. Papermill replaces that cell's values at runtime.
# Install papermill
pip install papermill
# Run notebook with parameters
papermill input_notebook.ipynb output_notebook.ipynb \
-p alpha 0.05 \
-p data_path /data/train.csv \
-p n_estimators 200
# Run from Python
import papermill as pm
pm.execute_notebook(
'analysis_template.ipynb',
'analysis_output_2026-04-02.ipynb',
parameters=dict(
alpha=0.05,
data_path='/data/train.csv',
n_estimators=200
)
) Papermill integrates naturally with Airflow, Prefect, and Luigi. Each DAG task can execute a notebook with different parameters, and the output notebooks serve as self-documenting execution logs — far richer than plain text logs.
Jupytext: Bidirectional Sync for Teams
Jupytext solves the version control problem by pairing every notebook with a lightweight text representation (.py, .md, or .R). When you edit either file, Jupytext synchronizes the changes to the other. Your Git diffs become readable Python code, code review in GitHub PRs becomes possible, and any developer can work in their preferred editor without losing notebook functionality.
# Install jupytext
pip install jupytext
# Pair an existing notebook with a .py file
jupytext --set-formats ipynb,py:percent analysis.ipynb
# Sync changes from .py back to .ipynb
jupytext --sync analysis.py
# Convert .py to .ipynb
jupytext --to notebook analysis.py
# Auto-pair all new notebooks (add to jupyter_notebook_config.py)
# c.ContentsManager.default_jupytext_formats = "ipynb,py:percent"
# The percent format looks like this in .py:
# %% [markdown]
# # Section Title
# %%
import pandas as pd
df = pd.read_csv('data.csv') The percent format is the most popular — cells are delimited by # %% markers, which VS Code, Spyder, and PyCharm all recognize natively. The light format is even cleaner but less compatible with editors.
CI/CD Integration
A robust notebook CI/CD pipeline typically combines nbstripout (to strip outputs before commit), nbconvert (to generate testable scripts), and pytest (to validate the generated code). Here is a complete GitHub Actions workflow:
# .github/workflows/notebook-tests.yml
name: Notebook Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install dependencies
run: |
pip install jupyter nbconvert nbstripout pytest
- name: Strip outputs
run: nbstripout notebooks/*.ipynb
- name: Convert notebooks to scripts
run: jupyter nbconvert --to script notebooks/*.ipynb --output-dir=tests/
- name: Run tests
run: pytest tests/ -v For pre-commit hooks, add nbstripout to your .pre-commit-config.yaml:
repos:
- repo: https://github.com/kynan/nbstripout
rev: 0.6.1
hooks:
- id: nbstripout Best Practices for Production Notebook Workflows
- Separate exploration from production: Keep exploratory notebooks in a
notebooks/folder and auto-generate scripts tosrc/for import and testing. - Always strip outputs before committing: Use nbstripout as a pre-commit hook to keep repository size manageable and diffs meaningful.
- Use cell tags consistently: Tag cells as
parameters,imports,visualization, orexcludeto enable selective export and papermill parameterization. - Test generated scripts in CI: Convert notebooks and run basic smoke tests (import, shape checks, output type checks) in every pull request.
- Pin nbconvert version: Conversion behavior can change between versions. Pin to a specific version in requirements-dev.txt to ensure reproducible builds.
- Consider Quarto for documentation: If your notebooks produce reports, Quarto extends the nbconvert concept with richer templating and multi-format publishing.
Choosing the Right Tool
Use nbconvert when you need a one-off or scripted export and don't need the scripts to stay in sync with the notebook. Use jupytext when your team works across notebooks and editors and you want clean Git history. Use papermill when you want to run notebooks as scheduled jobs with varying parameters and need execution records. Many mature data science teams use all three in combination — jupytext for development, nbconvert for CI tests, and papermill for production scheduling.
Frequently Asked Questions
What is the simplest way to convert a Jupyter notebook to a Python script?▼
The simplest method is using nbconvert from the command line: `jupyter nbconvert --to script notebook.ipynb`. This produces a .py file with all code cells preserved and markdown cells converted to comments. Install nbconvert with `pip install nbconvert` if it's not already available in your environment.
How do I strip outputs and metadata when converting notebooks?▼
Use the `--no-input` flag to omit input cells or combine nbconvert with nbstripout. For stripping outputs before conversion run: `nbstripout notebook.ipynb && jupyter nbconvert --to script notebook.ipynb`. You can also add a pre-commit hook with nbstripout to automatically strip outputs on every commit, keeping your repository clean.
What is the difference between nbconvert, jupytext, and papermill?▼
nbconvert is the standard one-way export tool — it converts .ipynb to .py, HTML, PDF, etc. Jupytext keeps notebooks and scripts in sync bidirectionally: edit either file and both stay updated, which is ideal for version control workflows. Papermill is for parameterized notebook execution — it runs notebooks with injected parameters and saves outputs, making it perfect for scheduled batch jobs without converting to scripts at all.
How can I integrate notebook-to-script conversion into a CI/CD pipeline?▼
Add a GitHub Actions step that runs `jupyter nbconvert --to script notebooks/*.ipynb` and commits the resulting .py files, or use them directly as pipeline stages. Alternatively, use Makefile targets or pre-commit hooks. For data science teams, a common pattern is to keep .ipynb for exploration, auto-generate .py for CI tests, and run pytest against the generated scripts to validate reproducibility.
How do I preserve cell tags or only export specific cells?▼
Tag cells in Jupyter with the 'tags' metadata field (e.g., 'parameters', 'injected-parameters', 'exclude'). Then use nbconvert with a custom Exporter or the TagRemovePreprocessor to skip tagged cells: `jupyter nbconvert --to script --TagRemovePreprocessor.enabled=True --TagRemovePreprocessor.remove_cell_tags='["exclude"]' notebook.ipynb`. This lets you keep exploratory cells in the notebook while exporting only production-ready code.
What is jupytext and why would I use it instead of nbconvert?▼
Jupytext pairs every .ipynb notebook with a lightweight .py (or .md, .R) file and keeps them synchronized. Unlike nbconvert which is one-shot, jupytext is designed for ongoing workflows. You can open the .py file in any editor, run it as a normal script, commit clean diffs to Git, and Jupyter will automatically sync changes back to the notebook. Enable it with `pip install jupytext` and configure it in jupyter_notebook_config.py or per-notebook via the Jupytext menu.
Related Products
on GumroadGitHub Actions CI/CD Templates Pack
12 production-ready GitHub Actions workflow templates covering Node.js, Python, Docker, multi-environment deployments, security scanning, and auto-changelog. Copy, paste, ship.
Buy on Gumroad →Developer Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →AI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →You Might Also Need
YAML Validator Pro
Advanced YAML validator with line-number error reporting, JSON preview, and schema hints for common YAML pitfalls. Free, runs in your browser.
Open free tool →
YAML to JSON Converter
Convert YAML to JSON and JSON to YAML online. Bidirectional conversion with syntax highlighting, error detection, and formatted output. Supports multi-document YAML and complex nested structures.
Open free tool →
TOML to JSON Converter
Convert TOML to JSON or JSON to TOML instantly. Supports sections, key-value pairs, arrays, booleans, and all scalar types. Free, runs 100% in your browser.
Open free tool →
More Free Tools
Related Articles
AI Agent Frameworks: AutoGPT vs CrewAI vs LangGraph vs AutoGen vs AgentGPT 2025
Comprehensive comparison of the top AI agent frameworks in 2025. Architecture, tool use, memory, orchestration, and code examples to help you pick the right framework for your project.
AI Agent Frameworks 2026: LangGraph vs CrewAI vs AutoGen vs OpenAI Agents SDK
Complete 2026 comparison of the top AI agent frameworks: LangGraph, CrewAI, AutoGen, and OpenAI Agents SDK. Architecture, multi-agent orchestration, tool use, memory systems, production examples, and a decision matrix.
CrewAI vs AutoGen vs LangGraph: Best Multi-Agent Framework in 2026
A production-focused comparison of CrewAI, AutoGen, and LangGraph for building multi-agent AI systems in 2026 — covering orchestration models, state management, ease of use, and real code examples.
Python vs JavaScript in 2026: When to Use Each for Backend and Automation
Python vs JavaScript comparison for backend development and automation. Covers async patterns, web frameworks, type systems, performance, and real-world use cases in 2026.
Authentication Security Tools 2026: Modern Auth Patterns, MFA, Passwordless, and OAuth2
Complete guide to authentication security tools in 2026. Covers Auth0, Clerk, NextAuth.js v5, JWT security, Passkeys/WebAuthn, TOTP authenticator apps, OAuth2/OIDC, session management, and building secure auth systems with Node.js and Python.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →