LoginSignup
112

More than 5 years have passed since last update.

Jupyter(IPython)でNoteBookをモジュールとしてインポートする方法

Last updated at Posted at 2016-08-26

Jupyterを使っていると別のnotebook(ipynbファイル)の関数や結果を使いまわしたくなりますよね。pythonモジュールとしてインポートする方法が公式にあったので紹介します。
(今後何回も使いそうなので自分の備忘録の意味も込めて)

公式のサイトの例:
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Importing%20Notebooks.html

やり方としてはnotebookを実行して結果をモジュールとして登録して、sys.meta_pathを使ってimportをフックして呼び出します。
importが呼ばれた時点でnotebookは実行されますが、元の状態を変えないようになっているので安心してください。

以下コードです。

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):
    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
        nb_path = nb_path.replace("_", " ")
        if os.path.isfile(nb_path):
            return nb_path

class NotebookLoader(object):
    def __init__(self, path=None):
        self.shell = InteractiveShell.instance()
        self.path = path

    def load_module(self, fullname):
        path = find_notebook(fullname, self.path)
        with io.open(path, 'r', encoding='utf-8') as f:
            nb = read(f, 4)
        mod = types.ModuleType(fullname)
        mod.__file__ = path
        mod.__loader__ = self
        mod.__dict__['get_ipython'] = get_ipython
        sys.modules[fullname] = mod
        save_user_ns = self.shell.user_ns
        self.shell.user_ns = mod.__dict__
        try:
          for cell in nb.cells:
            if cell.cell_type == 'code':
                code = self.shell.input_transformer_manager.transform_cell(cell.source)
                exec(code, mod.__dict__)
        finally:
            self.shell.user_ns = save_user_ns
        return mod

class NotebookFinder(object):
    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:
            key = os.path.sep.join(path)
        if key not in self.loaders:
            self.loaders[key] = NotebookLoader(path)
        return self.loaders[key]

これをnotebookutil.pyなどとして保存します。使うときは

import sys
import notebookutil as nbu
sys.meta_path.append(nbu.NotebookFinder())

とすれば、notebookをimportすることができます。

import mynotebook

関数やクラスが使えるのはもちろんですが、実際にnotebookを実行しているので変数なども実行時の値を持ったままimportできます。超便利!!

また、実行しているのでprintやplt.showなどが表示されていますが、notebookをimportしているセルをもう一度実行すれば見えなくなります。

これでより快適なJupyterライフが送れそうです。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
112