【问题标题】:In Jupyter Notebook, what is the best way to execute a function from another notebook?在 Jupyter Notebook 中,从另一个笔记本执行功能的最佳方式是什么?
【发布时间】:2020-03-11 03:26:42
【问题描述】:

我是 Jupyter Notebooks 的新手,并且正在使用 Anaconda 安装 Python 3.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

【问题讨论】:

  • 感谢@Wayne,从 .py 文件运行函数的解决方案(并且该解决方案在笔记本中适用于我)。我正在尝试从 .ipynb 文件运行一个函数。我试图实现 MEdwin 的评论,但它不起作用(错误消息“没有名为 mytest 的模块”)
  • @Wayne 有点用;但它会返回额外的输出(如果我只是从 .py 调用它就不会这样做),是的,它们在同一个工作目录中。
  • @wayne 删除返回语句,谢谢。如果您将 cmets 复制/粘贴到答案中,我会接受您的答案

标签: python function import jupyter-notebook


【解决方案1】:

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

另外,对于 Python 函数,你不想做return print。您可以删除 return 并保留 print 部分,或者返回您可以打印的字符串。

【讨论】:

  • 有趣的是,我刚刚测试了你的版本 #2 和我当前 Jupyter 和 Python 3.7 的笔记本/Python 组合,不介意return print。但是,正如您所见,最好避免。
  • 另外,您可以使用%%capture 作为%run 命令所在单元格的第一行添加,如果您想禁止来自其他笔记本的任何输入,请参阅我的 cmets here .
猜你喜欢
  • 1970-01-01
  • 2018-09-23
  • 1970-01-01
  • 2020-05-17
  • 2021-11-13
  • 2020-03-11
  • 2017-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多