如何在jupyter中调用同一文件夹下另一个ipynb文件中的函数

如何在jupyter中调⽤同⼀⽂件夹下另⼀个ipynb⽂件中的函数1、新建⼀个.py⽂件 Ipynb_importer.py
参考:
import io, os,sys,types
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
ip调度系统
with io.open(path, 'r', encoding='utf-8') as f:
nb = read(f, 4)
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_ns
# actually affect the notebook module's ns
save_user_ns = self.shell.user_ns
self.shell.user_ns = mod.__dict__
try:
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__)
finally:
self.shell.user_ns = save_user_ns
return mod
在打开的⽂件中file->download as->.py,这样就保存成.py⽂件了
注意这和把⽂件“a.ipynb” 在jupyter中直接rename成“a.py”是不⼀样的
全国身份证验证系统把这个⽂件放在同⼀⽂件夹下
2、在你正在书写的ipynb⽂件中import
例如,想要导⼊a这个ipynb中写的⼀个fun()函数,则⾸先import Ipynb_importer
import Ipynb_importer
import a
a.fun()
我是⼩⽩,记录我遇到问题的解决办法,以便⽇后查阅

本文发布于:2024-09-26 01:23:58,感谢您对本站的认可!

本文链接:https://www.17tex.com/tex/2/104175.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:系统   问题   遇到   验证
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议