在Python中调用Jupyter Notebook函数的两种实用方法
本文介绍在Python环境中调用Jupyter Notebook (.ipynb) 内函数的两种方法。首先通过自定义NotebookFinder模块实现直接导入,其次详解IPython中常用的行魔法与单元魔法命令,如%run、%timeit和%matplotlib inline等,帮助开发者提升交互效率与代码复用能力。
在Python中调用Jupyter Notebook函数的两种实用方法
Jupyter Notebook凭借其良好的交互性和模块化特性,深受众多Python开发者的喜爱。然而,.ipynb文件以JSON格式存储内容,而非标准的Python源代码格式,导致Python解释器无法直接解析。因此,如何在Python脚本中调用.ipynb文件中的模块成为了一个常见难题。
本文提供了一种解决方案:只需在工作目录下放置一个特定的Python文件,即可实现对其他Jupyter Notebook文件的正常调用。
Jupyter Notebook官方文档介绍了一种简单的方法,详见:http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Importing Notebooks.html
添加Jupyter Notebook解析文件
首先,创建一个名为Ipynb_importer.py的Python文件,具体代码如下:
import io, os,sys,types
from IPython import get_ipython
from nbformat import read
from IPython.core.interactiveshell import InteractiveShell
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]
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 = ['']
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 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
sys.meta_path.append(NotebookFinder())
调用Jupyter Notebook模块
在Jupyter Notebook文件中导入Ipynb_importer.py后,即可像调用普通Python文件一样调用其他.ipynb文件中的模块。例如,假设存在一个名为IpynbModule.ipynb的文件,其中定义了一个foo函数:

调用示例如下:

只要在工作目录下放置Ipynb_importer.py文件,即可正常调用所有的Jupyter Notebook文件。
这种方法的本质是利用一个Jupyter Notebook解析器先对.ipynb文件进行解析,将文件内的各个模块加载到内存中,供其他Python文件调用。
参考资料:
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Importing Notebooks.html
Jupyter Notebook魔法函数
魔法函数
使用魔法函数可以简单地实现一些纯Python代码难以高效完成的功能。
| 符号 | 功能 |
|---|---|
| %: | 行魔法函数,只对本行代码生效。 |
| %%: | Cell魔法函数,在整个Cell中生效,必须放于Cell首行。 |
| %lsmagic: | 列出所有的魔法函数 |
| %magic | 查看各个魔法函数的说明 |
| ? | 后面加上魔法函数名称,可以查看该函数的说明 |
一些常用魔法函数的示例:
| 魔法函数 | 作用 |
|---|---|
| %%writefile | 调用外部python脚本 |
| %run | 调用外部python脚本 |
| %timeit | 测试单行语句的执行时间 |
| %%timeit | 测试整个单元中代码的执行时间 |
| % matplotlib inline | 显示 matplotlib 包生成的图形 |
| %%writefile | 写入文件 |
| %pdb | 调试程序 |
| %pwd | 查看当前工作目录 |
| %ls | 查看目录文件列表 |
| %reset | 清除全部变量 |
| %who | 查看所有全局变量的名称,若给定类型参数,只返回该类型的变量列表 |
| %whos | 显示所有的全局变量名称、类型、值/信息 |
| %xmode Plain | 设置为当异常发生时只展示简单的异常信息 |
| %xmode Verbose | 设置为当异常发生时展示详细的异常信息 |
| %debug bug | 调试,输入quit退出调试 |
| %env | 列出全部环境变量 |
注意,这些命令仅在Python Kernel中适用,其他Kernel可能不适用。
Magic函数主要包含两大类:一类是行魔法(Line magic),前缀为%;另一类是单元魔法(Cell magic),前缀为%%。
%%writefile调用外部python脚本%run调用外部python脚本%timeit测试单行语句的执行时间%%timeit测试整个单元中代码的执行时间% matplotlib inline显示 matplotlib 包生成的图形%%writefile写入文件%pdb调试程序%pwd查看当前工作目录%ls查看目录文件列表%reset清除全部变量%who查看所有全局变量的名称,若给定类型参数,只返回该类型的变量列表%whos显示所有的全局变量名称、类型、值/信息
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









