2016-07-12 92 views
3

在IPython中是否有一种方法将import笔记本单元的内容看作是单独的模块?或者也可以让单元格的内容拥有自己的名称空间。IPython/Jupyter笔记本电脑可以像导入模块一样导入吗?

+1

是的,勾选[导入Jupyter笔记本作为模块](http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Importing%20Notebooks.html) – armatita

+1

@armatita您应该添加此作为答案:) –

+0

@ChristianTernus完成。我把它放在评论中,因为我以前从未尝试过(我不是Jupyter用户),但文档看起来非常完整。因此,我写了一个更完整的(从网站引用的东西)答案。谢谢。 – armatita

回答

2

@Mike,如你可以按照下面的链接继续导入Jupyter笔记本电脑作为一个模块有据可查的步骤评论中提到:

Importing Jupyter Notebooks as Modules

在链接,他们会提到所做的工作在Python中向用户提供hooks(现在用importlibimport system取代),以更好地定制导入机制。

作为这样他们提出的配方如下:

  • 负载笔记本文件到存储器
  • 创建一个空的模块
  • 在模块命名空间执行的每一个细胞

,他们提供他们自己的执行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

相关问题