Python ipynb 导入另一个 ipynb 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20186344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:48:48  来源:igfitidea点击:

ipynb import another ipynb file

pythonimportworkflowipython

提问by Andrew Harris

Interactive Python (ipython) is simply amazing, especially as you are piecing things together on the fly... and does it in such a way that it is easy to go back.

交互式 Python (ipython) 简直太棒了,尤其是当您动态地拼凑事物时……并且以易于返回的方式进行。

However, what seems to be interesting is the use-case of having multiple ipython notebooks (ipynb files). It apparently seems like a notebook is NOT supposed to have a relationship with other notebooks, which makes sense, except that I would love to import other ipynb files.

然而,似乎有趣的是拥有多个 ipython 笔记本(ipynb 文件)的用例。显然笔记本不应该与其他笔记本有关系,这是有道理的,除了我很想导入其他 ipynb 文件。

The only workaround I see is converting my *.ipynb files into *.py files, which then can be imported into my notebook. Having one file hold everything in a project is a bit weird, especially if I want to really push for code-reuse (isn't that a core tenet of python?).

我看到的唯一解决方法是将我的 *.ipynb 文件转换为 *.py 文件,然后可以将其导入到我的笔记本中。让一个文件保存项目中的所有内容有点奇怪,特别是如果我想真正推动代码重用(这不是 Python 的核心原则吗?)。

Am I missing something? Is this not a supported use case of ipython notebooks? Is there another solution I can be using for this import of an ipynb file into another notebook? I'd love to continue to use ipynb, but it's really messing up my workflow right now :(

我错过了什么吗?这不是 ipython 笔记本支持的用例吗?是否有另一种解决方案可以用于将 ipynb 文件导入另一个笔记本?我很想继续使用 ipynb,但它现在真的搞砸了我的工作流程:(

回答by germ13

The issue is that a notebooks is not a plain python file. The steps to import the .ipynbfile are outlined in the following: Importing notebook

问题是笔记本不是普通的 python 文件。导入.ipynb文件的步骤概述如下:导入笔记本

I am pasting the code, so if you need it...you can just do a quick copy and paste. Notice that at the end I have the import primesstatement. You'll have to change that of course. The name of my file is primes.ipynb. From this point on you can use the content inside that file as you would do regularly.

我正在粘贴代码,所以如果你需要它......你可以快速复制和粘贴。请注意,最后我有import primes语句。你当然必须改变它。我的文件名是primes.ipynb. 从现在开始,您可以像平常一样使用该文件中的内容。

Wish there was a simpler method, but this is straight from the docs.
Note: I am using jupyter not ipython.

希望有一个更简单的方法,但这直接来自文档。
注意:我使用的是 jupyter 而不是 ipython。

import io, os, sys, types
from IPython import get_ipython
from nbformat import current
from IPython.core.interactiveshell import InteractiveShell


def find_notebook(fullname, path=None):
    """find a notebook, given its fully qualified name and an optional path

    This turns "foo.bar" into "foo/bar.ipynb"
    and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar
    does not exist.
    """
    name = fullname.rsplit('.', 1)[-1]
    if not path:
        path = ['']
    for d in path:
        nb_path = os.path.join(d, name + ".ipynb")
        if os.path.isfile(nb_path):
            return nb_path
        # let import Notebook_Name find "Notebook Name.ipynb"
        nb_path = nb_path.replace("_", " ")
        if os.path.isfile(nb_path):
            return nb_path


class NotebookLoader(object):
    """Module Loader for Jupyter Notebooks"""
    def __init__(self, path=None):
        self.shell = InteractiveShell.instance()
        self.path = path

    def load_module(self, fullname):
        """import a notebook as a module"""
        path = find_notebook(fullname, self.path)

        print ("importing Jupyter notebook from %s" % path)

        # load the notebook object
        with io.open(path, 'r', encoding='utf-8') as f:
            nb = current.read(f, 'json')


        # create the module and add it to sys.modules
        # if name in sys.modules:
        #    return sys.modules[name]
        mod = types.ModuleType(fullname)
        mod.__file__ = path
        mod.__loader__ = self
        mod.__dict__['get_ipython'] = get_ipython
        sys.modules[fullname] = mod

        # extra work to ensure that magics that would affect the user_ns
        # actually affect the notebook module's ns
        save_user_ns = self.shell.user_ns
        self.shell.user_ns = mod.__dict__

        try:
        for cell in nb.worksheets[0].cells:
            if cell.cell_type == 'code' and cell.language == 'python':
                # transform the input to executable Python
                code = self.shell.input_transformer_manager.transform_cell(cell.input)
                # run the code in themodule
                exec(code, mod.__dict__)
        finally:
            self.shell.user_ns = save_user_ns
        return mod


class NotebookFinder(object):
    """Module finder that locates Jupyter Notebooks"""
    def __init__(self):
        self.loaders = {}

    def find_module(self, fullname, path=None):
        nb_path = find_notebook(fullname, path)
        if not nb_path:
            return

        key = path
        if path:
            # lists aren't hashable
            key = os.path.sep.join(path)

        if key not in self.loaders:
            self.loaders[key] = NotebookLoader(path)
        return self.loaders[key]

sys.meta_path.append(NotebookFinder())

import primes

回答by David Miller

There is no problem at all using Jupyter with existing or new Python .py modules. With Jupyter running, simply fire up Spyder (or any editor of your choice) to build / modify your module class definitions in a .py file, and then just import the modules as needed into Jupyter.

将 Jupyter 与现有或新的 Python .py 模块一起使用完全没有问题。运行 Jupyter 后,只需启动 Spyder(或您选择的任何编辑器)来构建/修改 .py 文件中的模块类定义,然后根据需要将模块导入 Jupyter。

One thing that makes this really seamless is using the autoreload magic extension. You can see documentation for autoreload here:

使这真正无缝的一件事是使用 autoreload 魔法扩展。您可以在此处查看 autoreload 的文档:

http://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html

http://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html

Here is the code to automatically reload the module any time it has been modified:

这是在修改模块时自动重新加载模块的代码:

# autoreload sets up auto reloading of modified .py modules
import autoreload
%load_ext autoreload
%autoreload 2

Note that I tried the code mentioned in a prior reply to simulate loading .ipynb files as modules, and got it to work, but it chokes when you make changes to the .ipynb file. It looks like you need to restart the Jupyter development environment in order to reload the .ipynb 'module', which was not acceptable to me since I am making lots of changes to my code.

请注意,我尝试使用先前回复中提到的代码来模拟将 .ipynb 文件作为模块加载,并使其正常工作,但是当您对 .ipynb 文件进行更改时它会卡住。看起来您需要重新启动 Jupyter 开发环境才能重新加载 .ipynb“模块”,这对我来说是不可接受的,因为我对代码进行了大量更改。

回答by Yash Bansal

The above mentioned comments are very useful but they are a bit difficult to implement. Below steps you can try, I also tried it and it worked:

上面提到的评论非常有用,但实施起来有点困难。您可以尝试以下步骤,我也尝试过并且有效:

  1. Download that file from your notebook in PY file format (You can find that option in File tab).
  2. Now copy that downloaded file into the working directory of Jupyter Notebook
  3. You are now ready to use it. Just import .PY File into the ipynb file
  1. 从您的笔记本中以 PY 文件格式下载该文件(您可以在“文件”选项卡中找到该选项)。
  2. 现在将下载的文件复制到 Jupyter Notebook 的工作目录中
  3. 您现在可以使用它了。只需将 .PY 文件导入到 ipynb 文件中

回答by johndodo

It is really simple in newer Jupyter:

在较新的 Jupyter 中这真的很简单:

%run MyOtherNotebook.ipynb

回答by anugrah

Please make sure that you also add a __init__.pyfile in the package where all your other .ipynb files are located.

请确保您还在__init__.py所有其他 .ipynb 文件所在的包中添加了一个文件。

This is in addition to the nbviewer link that minrkand syiprovided above.

这是除了在nbviewer链接minrksyi上方。

I also had some similar problem and then I wrote the solution as well as a link to my public google drive folder which has a working example :)

我也遇到了一些类似的问题,然后我编写了解决方案以及指向我的公共谷歌驱动器文件夹的链接,其中有一个工作示例:)

My Stackoverflow post with step by step experimentation and Solution:

我的 Stackoverflow 帖子带有分步实验和解决方案:

Jupyter Notebook: Import .ipynb file and access it's method in other .ipynb file giving error

Jupyter Notebook:导入 .ipynb 文件并在其他 .ipynb 文件中访问它的方法给出错误

Hope this will help others as well. Thanks all!

希望这也能帮助其他人。谢谢大家!

回答by axil

If you want to import A.ipynbfrom B.ipynbwrite

如果你想A.ipynbB.ipynbwrite导入

import import_ipynb
import A

in B.ipynb.

B.ipynb

The import_ipynbmodule I've created is installed via pip:

import_ipynb我创建的模块是通过 pip 安装的:

pip install import_ipynb

It's just one file and it strictly adheres to the official howtoon the jupyter site.

它只是一个文件,它严格遵守jupyter 站点上的官方 howto

PS It also supports things like from A import foo, from A import *etc

PS它还支持之类的东西from A import foofrom A import *

回答by Malgo

Run

!pip install ipynb

!pip install ipynb

and then import the other notebook as

然后将另一个笔记本导入为

from ipynb.fs.full.<notebook_name> import *

from ipynb.fs.full.<notebook_name> import *

or

或者

from ipynb.fs.full.<notebook_name> import <function_name>

from ipynb.fs.full.<notebook_name> import <function_name>

Make sure that all the notebooks are in the same directory.

确保所有笔记本都在同一目录中。

Edit 1: You can see the official documentation here - https://ipynb.readthedocs.io/en/stable/

编辑 1:您可以在此处查看官方文档 - https://ipynb.readthedocs.io/en/stable/

Also, if you would like to import only class & function definitions from a notebook (and not the top level statements), you can use ipynb.fs.defsinstead of ipynb.fs.full. Full uppercase variable assignment will get evaluated as well.

另外,如果你想从一个笔记本仅导入类和函数定义(而不是顶层语句),你可以使用ipynb.fs.defs的替代ipynb.fs.full。完整的大写变量赋值也将被评估。

回答by Fractale

You can use import nbimporterthen import notebookName

import nbimporter然后你可以使用import notebookName

回答by outofworld

Install ipynb from your command prompt

从命令提示符安装 ipynb

pip install import-ipynb

Import in your notebook file

导入您的笔记本文件

import import_ipynb

Now use regular import command to import your file

现在使用常规导入命令导入您的文件

import MyOtherNotebook