Skip to content

Instantly share code, notes, and snippets.

@teju85
Last active January 11, 2022 08:47
Show Gist options
  • Save teju85/31529bd0f28074e002996d8b703cb713 to your computer and use it in GitHub Desktop.
Save teju85/31529bd0f28074e002996d8b703cb713 to your computer and use it in GitHub Desktop.
A simple python script to convert .ipynb to cli output. Thereby enabling us to view the contents (text-only!) of a jupyter notebook from command-line.
#!/usr/bin/env python
import json
import sys
Width = 80
HeaderDemarc = "%s" % ("*" * Width)
CellDemarc = "%s" % ("-" * (Width // 2))
CellDemarc2 = CellDemarc * 2
OutputDemarc = "%s" % ("." * Width)
def printHeader(root):
print(HeaderDemarc)
if "nbformat" in root and "nbformat_minor" in root:
print("nbformat: v%d.%d" % (root["nbformat"], root["nbformat_minor"]))
else:
print("nbformat: NA")
if "metadata" in root and "language_info" in root["metadata"]:
info = root["metadata"]["language_info"]
print("language: %s (v%s)" % (info["name"], info["version"]))
print("#cells: %d" % len(root["cells"]))
print(HeaderDemarc)
print
def printCell(cell):
print(CellDemarc + " " + cell["cell_type"] + " " + CellDemarc)
if cell["cell_type"] == "markdown":
for line in cell["source"]:
print(line.rstrip())
elif cell["cell_type"] == "code":
cnt = cell["execution_count"]
cnt = cnt if cnt is not None else -1
tag = "In [%d]:" % cnt
spaces = " " * len(tag)
for line in cell["source"]:
print("%s %s" % (tag, line.rstrip()))
tag = spaces
if len(cell["outputs"]) > 0:
print(OutputDemarc)
for output in cell["outputs"]:
if "name" in output:
print("Target: %s" % output["name"])
if "text" in output:
for line in output["text"]:
print("%s %s" % (spaces, line.rstrip()))
print(CellDemarc2)
print
def printCells(root):
for cell in root["cells"]:
printCell(cell)
def main():
file = sys.argv[1]
with open(file, "r") as fp:
root = json.load(fp)
printHeader(root)
printCells(root)
return
if __name__ == "__main__":
main()
@teju85
Copy link
Author

teju85 commented Dec 13, 2019

Usage: ./ipynb2cli /path/to/notebook.ipynb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment