Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 678
Yixing Liu Avatar asked Mar 13 '19 05:03

Yixing Liu


2 Answers

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.

like image 152
Aswathy - Intel Avatar answered Nov 03 '22 02:11

Aswathy - Intel


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.

like image 37
Evidlo Avatar answered Nov 03 '22 01:11

Evidlo