从另一个Jupyter Notebook导入功能 [英] importing functions from another jupyter notebook

查看:341
本文介绍了从另一个Jupyter Notebook导入功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从另一个jupyter笔记本导入功能

I am trying to import a function from another jupyter notebook

在n1.ipynb中:

In n1.ipynb:

def test_func(x):
  return x + 1
-> run this

在n2.ipynb中:

In 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

请问有任何简单的方法吗?

Any easy ways to do this please?

推荐答案

nbimporter模块可在此处帮助我们

The nbimporter module helps us here:

pip install nbimporter

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

For example, with two notebooks in this directory structure:

/src/configuration_nb.ipynb

/src/configuration_nb.ipynb

analysis.ipynb

analysis.ipynb

/src/configuration_nb.ipynb:

/src/configuration_nb.ipynb:

class Configuration_nb():
    def __init__(self):
        print('hello from configuration notebook')

analysis.ipynb:

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文件导入和使用模块.

We can also import and use modules from python files.

/src/configuration.py

/src/configuration.py

class Configuration():
    def __init__(self):
        print('hello from configuration.py')

analysis.ipynb:

analysis.ipynb:

import nbimporter
from src import configuration

new = configuration.Configuration()

输出:

hello from configuration.py

这篇关于从另一个Jupyter Notebook导入功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆