VSCode: How to export a python file that was impor

2019-07-19 05:00发布

问题:

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.

回答1:

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

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 :-)



回答2:

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:

  • introduction article: convenient and easily tweakable Atom+Markdown+Pandoc+Jupyter experience,
  • 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.