【发布时间】: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