mwouts / jupytext

Jupyter Notebooks as Markdown Documents, Julia, Python or R scripts
https://jupytext.readthedocs.io
MIT License
6.65k stars 386 forks source link

Python API equivalent for `jupytext --to` CLI API #1066

Closed matthewfeickert closed 1 year ago

matthewfeickert commented 1 year ago

Is there a Python API equivalent for the CLI API jupytext --to for writing file to notebooks (instead of from notebooks to files)?

Obviously the answer at some level is "yes, as the CLI API is written in Python", but what I mean is is there an undocumented API that is the equivalent of

https://github.com/mwouts/jupytext/blob/79351dfac9fde7c72cc73d553f662b4887bc63f5/docs/using-library.md?plain=1#L42-L44

but going the other direction (converting and then writing a py:percent file to a notebook ipynb file)?

The CLI API for what I'm asking about is (using the names from the example from the docs above)

$ jupytext --to ipynb notebook.py

Apologies if I'm missing the obvious here.

mwouts commented 1 year ago

Hi @matthewfeickert , well you almost had the answer: You should 1. read the text notebook using jupytext.read, and then 2. write the notebook using either nbformat.write or jupytext.write.

Sorry I know this is a bit short but hopefully that helps?

matthewfeickert commented 1 year ago

Ugh, sorry @mwouts, I guess my head is not on straight today. Thanks very much for patiently spelling things out for me.

I think my brain read

https://github.com/mwouts/jupytext/blob/79351dfac9fde7c72cc73d553f662b4887bc63f5/docs/using-library.md?plain=1#L6

and thought "I'm reading a Python file not a notebook, so this isn't what I want" and kept going, even though the very next line is

https://github.com/mwouts/jupytext/blob/79351dfac9fde7c72cc73d553f662b4887bc63f5/docs/using-library.md?plain=1#L8-L9

My bad.

(Explicit example for anyone else):

from pathlib import Path

import jupytext

py_file_as_notebook = jupytext.read(Path("notebook.py").resolve())
jupytext.write(py_file_as_notebook, "notebook.ipynb", fmt="ipynb")