What's the best way to convert py to ipynb in code? or How can I programmatically convert py to ipynb

14 Replies, 1465 Views

Subject: What's the best way to convert py to ipynb in code?

Hey everyone,

I’ve got a bunch of .py scripts and wanna convert them to .ipynb notebooks *programmatically*. Tried a few things, but nothing’s sticking.

Anyone know a reliable method to convert py to ipynb in code? Preferably something lightweight—no manual steps.

Heard about `jupytext` and `p2j`, but not sure if they’re the best fit. Any tips or scripts you’ve used?

Thanks in advance!

(Also, if you’ve got a snippet to share, that’d be awesome 👀)
Hey! I've used `jupytext` before to convert py to ipynb in code, and it works like a charm.

Just install it (`pip install jupytext`), then run:
```python
jupytext --to notebook your_script.py
```

Super lightweight and no manual steps. Plus, it keeps the notebook structure clean.

If you need more control, check out their docs—tons of options for metadata and cell types.
Yo, `p2j` is another solid option if you wanna convert py to ipynb programmatically.

It’s a bit simpler than `jupytext` but gets the job done. Just:
```bash
p2j your_script.py
```

Only downside? Doesn’t handle super complex scripts well. But for basic stuff, it’s fire.
Honestly, I’d recommend `nbformat` if you want full control over the conversion process.

You can write a small script to parse the .py file and create cells dynamically. Here’s a snippet to get you started:
```python
import nbformat as nbf
nb = nbf.v4.new_notebook()
nb.cells.append(nbf.v4.new_code_cell("your code here"))
nbf.write(nb, "output.ipynb")
```

Bit more work, but super flexible.
If you’re lazy like me, just use VS Code’s built-in tools.

Open the .py file, click the "Convert to Jupyter Notebook" button (if you have the Jupyter extension).

No code needed, but yeah, it’s not *fully* programmatic. Still, saves time if you’re doing a one-off.
`jupytext` is the GOAT for this, no cap.

But if you wanna explore, `ipynb-py-convert` is another lib that does the reverse (ipynb to py), and you can tweak it to work backwards.

Not as straightforward, but hey, options are good.
For a no-frills solution, this script might help:
```python
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell().run_cell(open("script.py").read())
```

Save the output as .ipynb. Not perfect, but gets you 80% there.

---
Thanks for all the suggestions! Tried `jupytext` and it worked flawlessly for my use case.

Quick q tho—any way to preserve comments as markdown cells during the conversion? Right now they’re just getting dumped as code.

Also, big shoutout to the `nbformat` idea—gonna play with that for more custom stuff. Appreciate the help!



Users browsing this thread: 1 Guest(s)