Skip to content

Instantly share code, notes, and snippets.

@scivision
Last active April 22, 2026 20:31
Show Gist options
  • Select an option

  • Save scivision/e7326fdcfadb0c61b3f0adfff84f0f13 to your computer and use it in GitHub Desktop.

Select an option

Save scivision/e7326fdcfadb0c61b3f0adfff84f0f13 to your computer and use it in GitHub Desktop.
Strip Jupyter notebook outputs as Git pre-commit hook
#!/usr/bin/env python3
"""
Strip Jupyter notebook outputs as Git pre-commit hook
Using Git >= 2.54
git config --global hook.linter.event pre-commit
git config --global hook.linter.command '$HOME/linters/ipython.py'
"""
import subprocess
cmd = ["git", "diff", "--staged", "--name-only", "--diff-filter=ACMR", "-z"]
out = subprocess.check_output(cmd)
files = [f for f in out.decode("utf-8", errors="surrogateescape").split("\0") if f]
notebooks = [f for f in files if f.endswith(".ipynb")]
if notebooks:
cmd = ["jupyter", "nbconvert", "--clear-output", "--inplace", *notebooks]
print(" ".join(cmd))
subprocess.check_call(cmd)
subprocess.check_call(["git", "add", "--", *notebooks])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment