从另一个jupyter笔记本导入函数

vik*_*kky 7 python jupyter-notebook

我想从另一个jupyter笔记本导入一个函数

在n1.ipynb中:

def test_func(x):
  return x + 1
-> run this
Run Code Online (Sandbox Code Playgroud)

在n2.ipynb中:

%%capture
%%run n1.ipynb
test_func(2)
Run Code Online (Sandbox Code Playgroud)

错误:

NameError Traceback (most recent call last)<ipython-input-2-4255cde9aae3> in <module>()
----> 1 test_func(1)

NameError: name 'test_func' is not defined
Run Code Online (Sandbox Code Playgroud)

有什么简单的方法吗?

Opp*_*ppy 10

nbimporter模块在这里帮助我们:

pip install nbimporter
Run Code Online (Sandbox Code Playgroud)

例如,在此目录结构中有两个笔记本:

/src/configuration_nb.ipynb

analysis.ipynb

/src/configuration_nb.ipynb:

class Configuration_nb():
    def __init__(self):
        print('hello from configuration notebook')
Run Code Online (Sandbox Code Playgroud)

analysis.ipynb:

import nbimporter
from src import configuration_nb

new = configuration_nb.Configuration_nb()
Run Code Online (Sandbox Code Playgroud)

输出:

Importing Jupyter notebook from ......\src\configuration_nb.ipynb
hello from configuration notebook
Run Code Online (Sandbox Code Playgroud)

我们还可以从python文件导入和使用模块.

/src/configuration.py

class Configuration():
    def __init__(self):
        print('hello from configuration.py')
Run Code Online (Sandbox Code Playgroud)

analysis.ipynb:

import nbimporter
from src import configuration

new = configuration.Configuration()
Run Code Online (Sandbox Code Playgroud)

输出:

hello from configuration.py
Run Code Online (Sandbox Code Playgroud)