首页 > 解决方案 > 在 Jupyter Notebook 中,从另一个笔记本执行功能的最佳方式是什么?

问题描述

我是 Jupyter Notebooks 的新手,并且使用 Python 3.7 的 Anaconda 安装。从另一个笔记本执行功能的最佳方法是什么?我在这里找到了这个 2 年的答案,但我不知道是否有新的/更好的方法来安装 Anaconda(nbimporter 必须单独安装,它不在 Anaconda 中)。

这是笔记本中的代码/信息:

尝试#1(失败)

# working directory files:
# mytest.ipynb # this contains the function I am trying to call
# Untitled.ipynb # this is the Notebook I am working in


# mytest.ipynb contents:
def testfcn(x):
    return print("input is", str(x))


# Untitled.ipynb contents:
from mytest import testfcn
testfcn(4)

ModuleNotFoundError: No module named 'mytest'

尝试#2(好吧,不理想)

# Untitled.ipynb contents:

%run mytest.ipynb
testfcn(4)

# returns this, extra stuff:
0.019999999999999997
<class 'float'>
input is 4

标签: pythonfunctionimportjupyter-notebook

解决方案


此处的讨论包括 MEdwin 关于如何从您的笔记本中运行另一个笔记本的评论,然后您将能够在运行该%run other_notebook.ipynb步骤的笔记本中调用另一个笔记本的功能。
更新:我刚刚遇到了subnotebook项目,它可以让您像调用 Python 函数一样运行笔记本,传递参数并返回结果,包括输出内容。在这种情况下可能有用。更新结束。

此外,对于 Python 函数,您不想执行return print. 您可以删除return并留下该print部分,或者返回您可以打印的字符串。


推荐阅读