ipython笔记本中的python访问函数

时间:2015-04-22 18:45:06

标签: python ipython ipython-notebook

我有一个存储在.py文件中的函数,称之为my_methods。

def print_text(myText):
    print myText

我正在使用ipython notebook进行开发(本地服务器),而my_methods文件经常更改。

我想使用runipy通过引用my_methods中的函数的shell脚本运行其他ipython笔记本。例如,从shell脚本启动的一个ipython笔记本将如下所示:

import my_methods as mm

mm.print_text("print me")

如何设置它以便导入my_methods行可以从ipython笔记本(.ipynb)获取print_text函数,而不是.py版本?目前,我必须将my_methods笔记本下载为.py文件,导致版本控制问题(my_methods的.ipynb版本与下载的.py版本不同)

感谢您的帮助!

修改

因此,在阅读了作为答案显示的博客文章之后,我对find_notebook函数稍作修改。如果没有提供ipython笔记本的路径,我只是通过sys.path而不是当前目录读取。我也没有像他们那样在linux机器上运行,所以它让我更容易将所有添加的python文件保存在一个单独的目录中,该目录包含在我的路径变量中。我将以下代码保存在名为iPyLoader的模块中,然后在我的其他模块中首先导入它:

import io, os, sys, types
from IPython import get_ipython
from IPython.nbformat import current
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 = sys.path #EDITED HERE RATHER THAN CURRENT DIRECTORY
    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 IPython 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)

        print ("importing IPython notebook from %s" % path)

        # load the notebook object
        with io.open(path, 'r', encoding='utf-8') as f:
            nb = current.read(f, 'json')


        # 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.worksheets[0].cells:
            if cell.cell_type == 'code' and cell.language == 'python':
                # transform the input to executable Python
                code = self.shell.input_transformer_manager.transform_cell(cell.input)
                # 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 IPython 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]

sys.meta_path.append(NotebookFinder())

然后我的示例文件可能会运行这样的

import iPyLoader
import testnotebook as printer #this is an .ipynb file
printer.myprinter("test")

,输出为:

importing IPython notebook from C:\Python27\lib\testnotebook.ipynb
test

1 个答案:

答案 0 :(得分:0)

一个很好的近似值是here

简单的方法不存在,因为ipython笔记本不是普通的纯文本。

相关问题