3
votes

Probably a silly question, but I couldn't find it. Visual Studio Code editor has a really nice way to work with Jupyter Notebooks. I can edit the cells directly in vscode and run them. Now it would be easy to work with version control.

But I couldn't find a way to convert it back to a Notebook! How do I generate a notebook back from the generated python file?

I understand that the notebook wouldn't have the output cells in it.

4

4 Answers

2
votes

There is an option in the interactive Python window that has the notebook output:

Export option in interactive window

This is really cool, now you can work in a Python file and have a really nice interface with your version configuration system (Git).

Yes, it was a silly question :-)

1
votes

The Jupytext library supports the percent-based cell format used by VSCode-Python, as well as other text-based notebook interchange formats:

https://github.com/mwouts/jupytext

1
votes

If you need more control over how conversion to ipynb is done (or you need to have cross-references) then you can give a try to Pandoctools. It can export VSCode *.py documents to any Pandoc output format or to Jupyter notebook.

For example you can create and register Jupyter kernel. For example is can be named "nn". That should be the same kernel that you selected in VSCode (there you select it by path but VSCode still uses installed kernels specs under the hood). Then add hat to the Python file, split document to cells, provide settings and set Markdown cells (commented metadata line would export to pdf instead of ipynb; I recommend to open ipynb in nteract native app):

"""
---
kernels-map:
  py: nn
jupyter:
  kernelspec:
    display_name: nn
    language: python
    name: nn
pandoctools:
  # out: "*.pdf"
  out: "*.ipynb"
...

# Markdown section title 1

Some **static** Markdown text.
"""


# %% {echo=False}
import IPython.display as ds
import math
import sugartex as stex


# %% {markdown}
"""
# Markdown section title 2

The quick brown Fox jumps over the lazy dog.
"""


# %%
ds.Markdown(stex.pre(f'''

Some **dynamic** Markdown text with SugarTeX formula: ˎα^˱{math.pi:1.3f}˲ˎ.
It works because of the `Markdown` display option and `sugartex` Pandoc filter.
Acually `stex.pre` is redundant here but it is needed when the text is imported
or read from somewhere instead of being written in the same document.

'''))

Then convert the file via pandoctools: drag and drop file to pandoctools shortcut/executable or "open with" pandoctools executable.

Also see:

  • Two introduction articles are at the beginning of this README,
  • examples of input to output conversion that have cross-references!
  • how to use Pandoctools and it's CLI,
  • how to use Knitty that collects Jupyter outputs and change it's settings.
0
votes

Use jupytext library:

Install:

pip install jupytext

Now open CMD or internal terminal to the folder with your .py file

Run this:

jupytext --set-formats py:percent,ipynb filename.py