Skip to main content

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.

✓ nbconvert CLI ✓ Jupytext sync ✓ Papermill params ✓ CI/CD ready

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:

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

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.

Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

YAML Validator Pro YAML to JSON Converter TOML to JSON Converter TOML Validator XML Formatter & Validator YAML Diff Viewer SAML Request Decoder HTML to Markdown Converter JSON ↔ YAML Converter YAML to TOML Converter YAML to TOML Converter TOML to JSON Converter XML Prettifier HTML Entity Encoder / Decoder HTML Formatter & Minifier YAML Validator & Formatter Markdown to HTML Converter Helm Values Generator Pulumi Stack Config Generator Docker Compose Generator GitHub Actions Workflow Generator Kubernetes Manifest Generator GitHub Actions YAML Linter Kubernetes YAML Validator Helm Chart Linter CI/CD Pipeline Generator Ansible Playbook Builder Pulumi Modern IaC Guide Helm Values Validator CrewAI Agent Config Generator Helm Chart Values Generator Code Tools Markdown Preview & Editor Regex Tester Pro Unicode Character Lookup Dockerfile Generator Makefile Generator OpenAPI Validator ArgoCD App Health Checker OpenTelemetry Config Generator Prometheus Alert Rules Validator Kubernetes Resource Quota Calculator GitHub Actions Workflow Validator AI JSDoc Generator OpenAPI Schema Validator pnpm Workspace Generator K8s Resource Limits Calculator NATS Connection String Builder Playwright E2E Test Generator AI Model Benchmark Comparator Helm Values Builder Ansible Configuration Management Guide Sitemap.xml Validator Ansible Playbook Linter ArgoCD Application Generator GitHub Actions Matrix Builder Kubernetes Resource Request Calculator GitHub Actions Cron Builder HTML5 Canvas API Playground Particle System Config Generator LLM Benchmark Calculator LangGraph Workflow Visualizer Kubernetes RBAC Builder LangChain PromptTemplate Builder

Related Articles

Mar 27, 2026 · 16 min read

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.

Mar 27, 2026 · 16 min read

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.

Mar 27, 2026 · 15 min read

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.

Mar 24, 2026 · 10 min read

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.

Apr 2, 2026 · 21 min read

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.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$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.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

MIT licensed · Instant download · No subscription

See what's included → Browse all deals →