我正在尝试从另一个 jupyter notebook 导入一个函数
在 n1.ipynb 中:
def test_func(x):
return x + 1
-> run this
在 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
请问有什么简单的方法吗?
最佳答案
nbimporter 模块在这里帮助我们:
pip install nbimporter
例如,在这个目录结构中有两个笔记本:
/src/configuration_nb.ipynb
分析.ipynb
/src/configuration_nb.ipynb:
class Configuration_nb():
def __init__(self):
print('hello from configuration notebook')
分析.ipynb:
import nbimporter
from src import configuration_nb
new = configuration_nb.Configuration_nb()
输出:
Importing Jupyter notebook from ......\src\configuration_nb.ipynb
hello from configuration notebook
我们还可以从 python 文件中导入和使用模块。
/src/configuration.py
class Configuration():
def __init__(self):
print('hello from configuration.py')
分析.ipynb:
import nbimporter
from src import configuration
new = configuration.Configuration()
输出:
hello from configuration.py
关于python - 从另一个 jupyter notebook 导入函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50576404/