简体   繁体   English

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

[英]In Jupyter Notebook, what is the best way to execute a function from another notebook?

I am new to Jupyter Notebooks and using the Anaconda install for Python 3.7.我是 Jupyter Notebooks 的新手,并且使用 Python 3.7 的 Anaconda 安装。 What is the best way to execute a function from another notebook?从另一个笔记本执行功能的最佳方法是什么? I found this 2-year-old answer here , but I don't know if there is a new/better way to do it with the Anaconda install (nbimporter has to be installed separately, it's not in Anaconda).我在这里找到了这个 2 岁的答案,但我不知道是否有新的/更好的方法来安装 Anaconda(nbimporter 必须单独安装,它不在 Anaconda 中)。

Here is the code/info in the notebooks:这是笔记本中的代码/信息:

Try #1 (fail)尝试 #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'

Try #2 (okay, not ideal)尝试#2(好吧,不理想)

# Untitled.ipynb contents:

%run mytest.ipynb
testfcn(4)

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

The discussion here includes a comment by MEdwin on how to run another notebook from within yours and then you'll be able to call the functions of the other notebook in the noteboook where you ran the %run other_notebook.ipynb step.此处的讨论包括 MEdwin 关于如何从您的笔记本中运行另一个笔记本的评论,然后您将能够在运行%run other_notebook.ipynb步骤的笔记本中调用另一个笔记本的功能。
Update: I just came across the subnotebook project that let's you run a notebook as you would call a Python function, pass parameters and get results back, including output contents.更新:我刚刚遇到了子笔记本项目,它可以让您像调用 Python 函数一样运行笔记本,传递参数并返回结果,包括输出内容。 Might be useful in this context.在这种情况下可能有用。 END OF UPDATE.更新结束。

Additionally, for Python functions, you don't want to do return print .此外,对于 Python 函数,您不想执行return print You'd either remove the return and leave the print part or return the string that you could then print.您要么删除return并保留print部分,要么返回然后可以打印的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM