在Jupyter笔记本中,从另一个笔记本执行函数的最佳方式是什么?

2024-06-30 08:18:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Jupyter笔记本电脑和使用Anaconda安装Python3.7还不熟悉。从另一个笔记本执行函数的最佳方式是什么?我找到了this 2-year-old answer here,但我不知道是否有一种新的/更好的方法来安装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

Tags: theinputiscontents笔记本jupyteranacondathis
1条回答
网友
1楼 · 发布于 2024-06-30 08:18:16

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

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

相关问题 更多 >