gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:20:47 28 4
gpt4 key购买 nike

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com