python学习系列二:jupyter notebook中调用其他.ipynb模块内的变量或者函数
程序员文章站
2022-05-28 11:19:16
...
大致方法有三:
1、直接将被掉文件转为.py格式
可在终端运行:jupyter nbconvert --to python XXX.ipynb #XXX.ipynb就是你想调用的.ipynb文件
2、在每个.ipynb文件后面添加自动转换命令
try:
!jupyter nbconvert --to python import_test.ipynb #注意这是shell命令,不要忘记加!
except:
pass
3、①、在你的工作路径下加入如下文件:
Ipynb_importer.py
当然这个文件也是在jupyter中新建的.ipynb文件转过来的,如果是.ipynb格式还是不行的
这个文件的代码,完全复制如下代码:
#!/usr/bin/env python
# coding: utf-8
# In[12]:
import io, os,sys,types
from IPython import get_ipython
from nbformat import read
from IPython.core.interactiveshell import InteractiveShell
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:
# 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):
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):
def __init__(self, path=None):
self.shell = InteractiveShell.instance()
self.path = path
def load_module(self, fullname):
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())
一定要注意缩进,不然会报错,我开始的时候及时 exec(code, mod.__dict__)这一行没有缩进到于上一行代码对其,导致报错:
SyntaxError: unexpected EOF while parsing
把上面的缩进四个空格之后,就可以了
可以先自己在jupyter中按Enter+shift运行试下
②、在你想引用的其他.ipynb的文件内加入
import Ipynb_importer
import some_module
"""
some_module就是你想引用的.ipynb文件,这种方法有个缺点,就是tab键不能自动补全这个文件名,要你自己一点点输入,而且后面的调用也不会自动补全,要手动输入
"""
以上三种方法由易到难,每种都亲测有效,你可以自己选择用哪种方法
上一篇: R语言中的各种更新方法
下一篇: 记一次简单的渗透实战(手工SQL注入)