Python 如何将一个Jupyter笔记本导入另一个

Python 如何将一个Jupyter笔记本导入另一个,python,ipython,jupyter-notebook,Python,Ipython,Jupyter Notebook,很明显,把一个Jupyter笔记本换成另一个是可能的。链接页面中有很多代码可以执行此操作。我是否应该将该代码添加到导入笔记本中?这一页不清楚。它应该是一个通用的解决方案,所以将所有这些代码添加到所有导入其他笔记本的笔记本中是没有意义的。任何帮助都将不胜感激。谢谢 是的,如果需要,您可以将所有代码添加到笔记本中 是的,你不应该这样做作为一个普遍的解决方案 笔记本是一个复杂的结构,正如文本细节中提到的(我认为它是JSON)。它可以包含python代码,也可以包含magics—cython、bash、

很明显,把一个Jupyter笔记本换成另一个是可能的。链接页面中有很多代码可以执行此操作。我是否应该将该代码添加到导入笔记本中?这一页不清楚。它应该是一个通用的解决方案,所以将所有这些代码添加到所有导入其他笔记本的笔记本中是没有意义的。任何帮助都将不胜感激。谢谢

是的,如果需要,您可以将所有代码添加到笔记本中

是的,你不应该这样做作为一个普遍的解决方案

笔记本是一个复杂的结构,正如文本细节中提到的(我认为它是JSON)。它可以包含python代码,也可以包含magics—cython、bash、latex等—这是python内核无法理解的。实际上,您必须复制普通Python导入过程的一部分功能,因为Python本机无法理解Ipython笔记本中有Python代码

然而。。。通常,如果您有大量Python代码,您会将其拆分为模块,然后导入模块。这些工作正常,因为它是一个普通的Python导入

例如,一旦加载了告诉它如何理解笔记本的代码,实际的导入就只是

导入nbpackage.mynotebook

我们可以对模块导入代码使用相同的技术-
find_notebook
NotebookLoader
可以放入助手模块(例如
helper.py
),您所要做的就是,从笔记本中使用
from helper import NotebookFinder

我怀疑在导入过程中,您仍然需要从笔记本内部调用
sys.meta\u path.append(NotebookFinder())

以下是如何使用导入功能创建从笔记本中绘制的API的具体示例:

创建一个笔记本。我们称之为扫描器.ipynb:

import os, sys
def scanner(start):
    for root, dirs,files in os.walk(start):
        # remove any already processed file
        if 'done' in dirs:
            dirs.remove('done')
        for names in files:
            name, ext = os.path.splitext(names)
            # only interested in media files
            if ext == '.mp4' or ext == '.mkv':
                print(name)
创建一个名为
reuse.py
的常规python文件这是您的通用可重用Ipython导入模块

#! /usr/env/bin python
# *-* coding: utf-8 *-*

import io, os, sys, types
from IPython import get_ipython
from nbformat import read
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 = read(f, 4)


        # 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.cells:
            if cell.cell_type == 'code':
                # transform the input to executable Python
                code = self.shell.input_transformer_manager.transform_cell(cell.source)
                # 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]
创建将上面的加载程序与上面的笔记本连接起来的特定API文件。称它为scan\u api.py:

# Note the python import here
import reuse, sys

# This is the Ipython hook
sys.meta_path.append(reuse.NotebookFinder())
import scanner
# And now we can drawn upon the code
dir_to_scan = "/username/location"
scanner.scanner(dir_to_scan)

两行代码的简单解决方案

使用python中的“nbimporter”包在笔记本B中导入另一个笔记本A(或其功能)。您可以使用命令-pip install nbimporter安装“nbimporter”

假设有两个笔记本A.ipynb和B.ipynb。我们正在尝试将笔记本A(或其功能)导入B代码中,下面的示例应该可以解决这个问题

内置笔记本B.ipynb

import nbimporter
import A  # or do this --> from A import func1

并不是因为我有很多代码。我有两个笔记本,想将一个笔记本导入另一个笔记本。但是假设我想把其中一个做成一个模块,然后导入它。需要做什么?@russabbot你不需要把笔记本变成一个模块,你需要把导入代码变成一个模块。隐马尔可夫模型。。。如果您想公开类似于API的特定功能,可以将笔记本变成模块。然后使用导入功能创建一个标准的“.py”文件。我看能否用一个具体的例子来编辑我的答案。我的问题是,我似乎无法找到我要导入的笔记本所在的目录。我有我想导入的笔记本(笔记本A)和我想导入的笔记本(笔记本B)在同一个谷歌硬盘目录中。但当我在colab中打开笔记本B时,系统(使用!pwd)说它在
/content
中,它看不到笔记本A。它所能看到的只是
样本数据
。我如何把自己放在正确的目录中?我也不能
!cd
直接到正确的目录,即使我给出完整路径:
!cd“C:\Users\rabbott\Google Drive\Colab笔记本”