Yixing Liu
Yixing Liu

Reputation: 2429

How can I import code and markdown cells from Python to Jupyter notebook?

For version control reasons, I must save my code in .py files.

I would like to be able to able to import cells of Python code and Markdown documentation from .py files to Jupyter notebook.

For example, I would like to use Jupyter notebook to run my report code, which has multiple sections of code and documentation.

I am aware of the built-in %run and %load in Jupyter:

%run report.py
%load report.py

%run and %load run/load everything into one cell. I am looking for a solution which allows me to split a single python file to multiple notebook cells.

Thank you!

Upvotes: 9

Views: 2965

Answers (3)

Evidlo
Evidlo

Reputation: 334

I wrote an iPython extension which does this: ipython-cells.

It can be used like this:

$ pip install ipython-cells
>>> %load_ext ipython_cells
>>> %load_file test.py
>>> %cell_run 1
hello
>>> %cell_run 2
world

And the test file test.py

# In[1]
print('hello')
# In[2]
print('world')

It also supports cell range execution and Spyder cell delimiters. See the readme.

Upvotes: 1

neves
neves

Reputation: 39173

Try the built in

%load script.py

And do a little editing. Good If It has little markdown.

Learn the keyboard shortcut to split cell and convert to markdown.

Upvotes: 0

Aswathy - Intel
Aswathy - Intel

Reputation: 648

Have used 'p2j' to convert python file (.py) to ipython notebook file (.ipynb).

Try using the below steps:

  1. pip install p2j
  2. p2j your_python_file.py

For more details, refer https://github.com/raibosome/python2jupyter

Hope this helps.

Upvotes: 8

Related Questions