从另一个 jupyter notebook 导入函数 [英] importing functions from another jupyter notebook
本文介绍了从另一个 jupyter notebook 导入函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从另一个 jupyter notebook 导入函数
I am trying to import a function from another jupyter notebook
在 n1.ipynb 中:
In n1.ipynb:
def test_func(x):
return x + 1
-> run this
在 n2.ipynb 中:
In n2.ipynb:
%%capture
%%run n1.ipynb
test_func(2)
错误:
NameError Traceback (most recent call last)<ipython-input-2-4255cde9aae3> in <module>()
----> 1 test_func(1)
NameError: name 'test_func' is not defined
请问有什么简单的方法吗?
Any easy ways to do this please?
推荐答案
nbimporter 模块在这里帮助我们:
The nbimporter module helps us here:
pip install nbimporter
例如,在这个目录结构中有两个笔记本:
For example, with two notebooks in this directory structure:
/src/configuration_nb.ipynb
/src/configuration_nb.ipynb
分析.ipynb
/src/configuration_nb.ipynb:
/src/configuration_nb.ipynb:
class Configuration_nb():
def __init__(self):
print('hello from configuration notebook')
analysis.ipynb:
analysis.ipynb:
import nbimporter
from src import configuration_nb
new = configuration_nb.Configuration_nb()
输出:
Importing Jupyter notebook from ......srcconfiguration_nb.ipynb
hello from configuration notebook
我们还可以从 python 文件中导入和使用模块.
We can also import and use modules from python files.
/src/configuration.py
/src/configuration.py
class Configuration():
def __init__(self):
print('hello from configuration.py')
analysis.ipynb:
analysis.ipynb:
import nbimporter
from src import configuration
new = configuration.Configuration()
输出:
hello from configuration.py
这篇关于从另一个 jupyter notebook 导入函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文