从另一个 jupyter notebook 导入函数

新手上路,请多包涵

我正在尝试从另一个 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

请问有什么简单的方法吗?

原文由 data_person 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

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

原文由 Oppy 发布,翻译遵循 CC BY-SA 4.0 许可协议

我为将函数导入 Jupyter notebook 所做的一些事情是在单独的 Python .py 文件中编写函数,然后在 notebook 中使用魔术命令 %run。这是至少一种方法的示例:

notebook.ipynb 和 helper_functions.py 都在同一个目录中。

helper_functions.py:

 def hello_world():
    print('Hello world!')

笔记本.ipynb:

 %run -i helper_functions.py
hello_world()

notebook.ipynb 输出:

 Hello world!

%run 命令告诉 notebook 运行指定的文件,-i 选项在 IPython 命名空间中运行该文件,这在这个简单的示例中并没有真正意义,但如果您的函数与 notebook 中的变量交互则很有用。如果我没有为您提供足够的详细信息,请查看 文档

对于它的价值,我还尝试在外部 .ipynb 文件而不是外部 .py 文件中运行函数定义,它对我有用。如果您想将所有内容都保存在笔记本中,可能值得探索。

原文由 Kurt Eulau 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题