调⽤jupyternotebook⽂件内的函数⼀种简单⽅法
python开发环境jupyter notebook良好的交互式和模块化受到很多python开发⼈员的青睐,但是jupyter notebook是以json格式保存⽂件内容的,⽽不是python⽂件那样的普通格式,所以不能直接被python解析器解析,如何调⽤.ipynb中的module也成为⼀个问题。本⽂介绍⼀种⽅法,使得只要在我们的⼯作⽬录下放置⼀个python⽂件,就可以正常调⽤其他jupyter notebook⽂件。
Jupyter Notebook官⽹介绍了⼀种简单的⽅法:
添加jupyter notebook解析⽂件
⾸先,创建⼀个python⽂件,例如Ipynb_importer.py,代码如下:
import io, os,sys,types
az和8按ascii码值升序排序from IPython import get_ipython
from nbformat import read
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 = place("_", " ")
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 dules
# if name dules:
# dules[name]
mod = types.ModuleType(fullname)
mod.__file__ = path
mod.__loader__ = self
mod.__dict__['get_ipython'] = get_ipython
# extra work to ensure that magics that would affect the user_nspython解析json文件
# actually affect the notebook module's ns
save_user_ns = self.shell.user_ns
self.shell.user_ns = mod.__dict__
try:
update语句用来for cell lls:
ll_type == 'code':
# transform the input to executable Python
code = self.shell.input_ansform_cell(cell.source)
# run the code in themodule
exec(code, mod.__dict__)c语言编写登录界面
finally:
self.shell.user_ns = save_user_ns
return mod
调⽤jupyter notebook module
在我们的jupyter notebook⽂件⾥调⽤Ipynb_importer.py,接下来我们就可以像调⽤普通python⽂件⼀样调⽤其他.ipynb⽂件⾥的module了,例如有⼀个IpynbModule.ipynb⽂件,⾥⾯定义了⼀个foo函数:八进制15乘12怎么算
调⽤例⼦如下:
只要在我们的⼯作⽬录下放置Ipynb_importer.py⽂件,就可以正常调⽤所有的jupyter notebook⽂件。 这种⽅法的本质就是使⽤⼀个jupyter notenook解析器先对.ipynb⽂件进⾏解析,把⽂件内的各个模块加载到内存⾥供其他python⽂件调⽤。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论