可以将IPython / Jupyter笔记本单元导入,就好像它是模块一样吗?

时间:2016-07-12 19:54:22

标签: python ipython ipython-notebook jupyter-notebook

在IPython中是否有一种方法可以将import笔记本单元格的内容视为一个单独的模块?或者,也可以让单元格的内容拥有自己的命名空间。

1 个答案:

答案 0 :(得分:3)

@Mike,如评论中所述,您可以按照以下链接中记录良好的步骤将Jupyter Notebook作为模块导入:

Importing Jupyter Notebooks as Modules

在链接中,他们将提到在Python中完成的工作,为用户提供hooks(现已取代importlibimport system),以便更好地自定义导入机制。

他们建议的食谱如下:

  
      
  • 将笔记本文档加载到内存中
  •   
  • 创建一个空模块
  •   
  • 执行Module名称空间中的每个单元格
  •   

,他们为Notebook Loader提供了自己的实现(如果代码都是纯python则不需要):

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

此处还有Notebook Finder的实施:

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] 

最后一步是新模块的registration

sys.meta_path.append(NotebookFinder())

然而,所有这些都是本回答中第一个链接的直接引用。该文档构建良好,可为displaying notebooks或处理packages等其他内容提供答案。