在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

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

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

最新更新