2016-07-12 91 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

相關問題