Best way to convert .ipynb to .py in VSCode

Question:

I’m looking for a good way to convert .ipynb to .py files in VSCode. So far I’ve tried:

  • the "Export As" Option built into vscode. Not ideal as it produces the following at the start of the script, as well as "Run Cell", "Run Below", etc. buttons/links:

"To add a new cell, type ‘# %%’ To add a new markdown cell, type ‘# %%
[markdown]’ %% from IPython import get_ipython"

  • nbconvert. I usually insert this as a command in the script itself (https://stackoverflow.com/a/19779226/14198216) so it’s automatically converted and saved once run. But this also leaves "Run Cell" etc, as well as execution markings (ex: "In [1]")

  • jupytext. I also usually insert this as a command. At the start of the .py, it produces:

– coding: utf-8 –
— jupyter: jupytext:
text_representation:

Is there a nice, minimalist solution that doesn’t insert a bunch of gunk (which needs to be manually edited out) in the .py version of my notebooks and can be easily/automatically executed from the notebook itself? This could also be setting tweaks that I’m currently unaware of that can make one of the things I mentioned work better.

Thanks in advance.

Asked By: Isaac Liu

||

Answers:

We can add the following settings in "settings.json", the generated python file will not have "Run Cell", "Run Above", "Debug Cell":

"jupyter.codeLenses": " ",

enter image description here

Answered By: Jill Cheng

I found that there is a way to export right within VS Code:

https://code.visualstudio.com/docs/python/jupyter-support-py

Export a Jupyter notebook

In addition to opening a Jupyter notebook, you can also use one of the
following commands from the Command Palette (⇧⌘P) to export content
from a Python file in VS Code to a Jupyter notebook (with the .ipynb
extension).

  • Jupyter: Export Current Python File as Jupyter Notebook: creates a Jupyter notebook from the contents of the current file, using the # %% and # %% [markdown] delimiters to specify their respective cell types.
  • Jupyter: Export Current Python File and Output as Jupyter Notebook: creates a Jupyter notebook from the contents of the current file and includes output from code cells.
  • Jupyter: Export Interactive Window as Jupyter Notebook: creates a Jupyter notebook from the contents of the Python Interactive window.

After exporting the contents, VS Code displays a prompt through which you can open the notebook in a browser.

Answered By: u5easdrctd

First, you need to install the Jupyter package:

https://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter

Second open "Command Palette" (⇧⌘P) and search for this line:
Jupyter: Export to Python Script
enter image description here

Answered By: Mohamad Hamouday

Converting to .py by Command Palette will open a file, just select one of the markdowns # %%, change all occurrences (Ctrl+F2), and remove all # %% at once. This will remove all "Run Cell" etc… Save file.

Answered By: jazzyjoint