我正在尝试从另一个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
analysis.ipynb
/src/configuration_nb.ipynb:
class Configuration_nb():
def __init__(self):
print('hello from configuration notebook')
analysis.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')
analysis.ipynb:
import nbimporter
from src import configuration
new = configuration.Configuration()
输出:
hello from configuration.py
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句