python - 从另一个 jupyter notebook 导入函数

标签 python 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

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

最佳答案

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/

相关文章:

python - Graphviz 错误 - 如何使用 Python 3.3 查看图形?

python - 如何在 jupyter notebook markdown 单元格中插入代码输出?

python - 使用 jupyter 笔记本需要互联网吗?

apache-spark - Spark Standalone - Tmp 文件夹

python - 在django中将注册表单填写到数据库后如何存储用户选择的单选按钮值?

python - 用于 OAuth 身份验证的 WSGI 中间件

python - 如何简单地让 python 将 "\xaa\xbb\xcc\xdd"打印为 0xddccbbaa?

python - 如何用新行扩展Excel单元格?

pycharm - 如何在 pycharm 2018.1 上使用带有 jupyter notebook 的远程解释器

查找连续重复的单词时 Python 后视正则表达式 "fixed-width pattern"错误