Import .py flie into Jupyter Notebook line by line

2019-08-27 03:27发布

I prefer to write my python code on VSCode because of its intellisense and autocomplete features. But I would rather see and debug the code on a Jupyter notebook to better visualize the data I am working with.

I know I can load any file into Jupyter by using the magical %load or %loadpy commands. But they load the entire file into a single cell.

Since I wanted to see the intermediary results of certain operations, I would like to import the file in such a way that each line on the file is assigned to a cell on the notebook. Unless it's a function or conditional statement (in other words, anything with indentation); in these cases it should add the whole block into one cell.

How can I do that?

2条回答
唯我独甜
2楼-- · 2019-08-27 04:03

You can create a new Jupyter notebook file programmatically with nbformat module. Let me demonstrate all the steps with a working code.

Below are cells in a Jupyter notebook. This cell has a magic command that creates a file, named script001.py.

%%writefile script001.py
x = 10
print('x is: %s' % x)
y = 20
print('y is: %s' % y)
z = x+y
print('z is: %s' % z)

Code in the second cell below creates a new notebook, named split_cells.ipynb.

import nbformat as nbf

# create notebook object
nb2 = nbf.v4.new_notebook()

# prep cells' content for the new notebook
code = []
with open('script001.py') as fi:
    for aline in fi:
        code.append(aline.rstrip())

# take each line of code as single cells
nb2['cells'] = [nbf.v4.new_code_cell(ea) for ea in code]

# name of notebook to create
fname = 'split_cells.ipynb'

# create new notebook file
with open(fname, 'w') as fj:
    nbf.write(nb2, fj)

When you open the new notebook, split_cells.ipynb, you will have the cells like this:

In[]: x = 10

In[]: print('x is: %s' % x)

In[]: y = 20

In[]: print('y is: %s' % y)

In[]: z = x+y

In[]: print('z is: %s' % z)

This notebook is ready to run as you wish. Hope it helps.

查看更多
forever°为你锁心
3楼-- · 2019-08-27 04:04

AFAIK, there is no way to do this upon loading your file into a Jupyter notebook. However, you can easily split your big cell into multiple cells, by using ctrl+shift+-. This will split your cell at the position where your cursor is located at that time.

I don't know how big your files are, but it is a really fast and efficient way to split cells so maybe that works for you =)

查看更多
登录 后发表回答