逐行将.py flie导入Jupyter Notebook [英] Import .py flie into Jupyter Notebook line by line

查看:138
本文介绍了逐行将.py flie导入Jupyter Notebook的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我更喜欢在VSCode上编写我的python代码,因为它具有智能和自动完成功能.但是我宁愿在Jupyter笔记本上查看和调试代码,以更好地可视化我正在使用的数据.

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.

我知道我可以使用神奇的%load%loadpy命令将任何文件加载到Jupyter中.但是他们将整个文件加载到单个单元格中.

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.

我该怎么做?

推荐答案

您可以使用nbformat模块以编程方式创建新的Jupyter笔记本文件.让我用一个有效的代码演示所有步骤.

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

下面是Jupyter笔记本中的单元格.该单元格具有一个魔术命令,该命令会创建一个名为script001.py的文件.

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)

下面第二个单元格中的代码创建一个名为split_cells.ipynb的新笔记本.

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)

打开新笔记本split_cells.ipynb时,将具有以下单元格:

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.

这篇关于逐行将.py flie导入Jupyter Notebook的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆