Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a python script with cell delimiters to a jupyter notebook? [duplicate]

I mostly use Spyder for my data analysis and am quite satisfied with it. There you can use the cell functionality of Jupyter Notebooks in normal python scripts using # %% to delimit individual code cells (and also execute blocks). The same thing is also possible in Atom with Hydrogen.

What I am looking for is a way to convert these scripts into a jupyter notebook, automaticlally splitting cells at each # %%. The notebook I would use to document, explain and share my workflow by inserting some markdown and possibly saving as pdf or html.

Can the conversion be done automatically? Is this perhaps doable with nbconvert? (I only use it the other way around: jupyter -> python)

like image 475
flurble Avatar asked Apr 30 '19 11:04

flurble


People also ask

How do you duplicate a cell in Jupyter Notebook?

X will cut the selected cell. C will copy the selected cell. V will paste the cell which is being copied/cut. Shift + V paste cells above.

Can I duplicate a Jupyter Notebook?

New Notebook: Start a new notebook (another browser panel like this one) Open...: Select a file to open from the notebook Files view. Make a Copy...: Copy the current notebook completely into another browser panel.

What is %% capture in Jupyter?

IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable. from __future__ import print_function import sys. By default, %%capture discards these streams. This is a simple way to suppress unwanted output.


1 Answers

there is jupytext (also available on pypi) that can convert from ipynb to several formats and back.

when jupytext is installed you can use

$ jupytext --to notebook test.py

in order to generate test.ipynb.

jupytext has a lot more interesting features that can come in handy when working with notebooks.

like image 157
hiro protagonist Avatar answered Sep 30 '22 13:09

hiro protagonist