如何加载/编辑/运行/保存文本文件(.py)到IPython笔记本单元格?

如何加载/编辑/运行/保存文本文件(.py)到IPython笔记本单元格?

问题描述:

我最近转向使用IPython笔记本作为我工作流程的一部分。但是,我没有成功地找到一种方法将.py文件导入到打开的IPython笔记本的各个单元格中,以便它们可以编辑,运行然后保存。可以这样做吗?

I've recently moved over to using IPython notebooks as part of my workflow. However, I've not been successful in finding a way to import .py files into the individual cells of an open IPython notebook so that they can edited, run and then saved. Can this be done?

我发现这个告诉我如何将.py文件作为新笔记本导入,但这不符合我想要实现的目标。

I've found this in the documentation which tells me how to import .py files as new notebooks but this falls short of what I want to achieve.

我们非常感谢任何建议。

Any suggestions would be much appreciated.


编辑:从IPython 3(现在的Jupyter项目)开始,笔记本有一个文本编辑器,可以作为
加载/编辑/保存文本文件的更方便的替代方案。

EDIT: Starting from IPython 3 (now Jupyter project), the notebook has a text editor that can be used as a more convenient alternative to load/edit/save text files.

可以使用魔术命令%load 在笔记本单元格中加载文本文件。

A text file can be loaded in a notebook cell with the magic command %load.

如果执行包含以下内容的单元格:

If you execute a cell containing:

%load filename.py

将加载 filename.py 的内容下一个细胞。您可以照常编辑和执行它。

the content of filename.py will be loaded in the next cell. You can edit and execute it as usual.

要将单元格内容保存回文件,请添加cell-magic %% writefile filename.py 在单元格的开头并运行它。请注意,如果已经存在具有相同名称的文件,它将被静默覆盖

To save the cell content back into a file add the cell-magic %%writefile filename.py at the beginning of the cell and run it. Beware that if a file with the same name already exists it will be silently overwritten.

要查看任何魔术命令的帮助,请添加?:喜欢%load? %% writefile?

To see the help for any magic command add a ?: like %load? or %%writefile?.

有关魔术函数的一般帮助,请输入%magic
有关可用魔术函数的列表,请使用%lsmagic。有关其中任何一个的
的说明,请键入%magic_name ?,例如'%cd?'。

For general help on magic functions type "%magic" For a list of the available magic functions, use %lsmagic. For a description of any of them, type %magic_name?, e.g. '%cd?'.

参见:魔术功能