python - 在 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
步骤的笔记本中调用另一个笔记本的功能。
更新:我刚刚遇到了subnotebook项目,它可以让您像调用 Python 函数一样运行笔记本,传递参数并返回结果,包括输出内容。在这种情况下可能有用。更新结束。
此外,对于 Python 函数,您不想执行return print
. 您可以删除return
并留下该print
部分,或者返回您可以打印的字符串。
推荐阅读
- machine-learning - 反相前馈神经网络
- r - 在 Mapview 中绘制点数据 - 点符号大小的非线性比例?
- c# - 如何从 JsonConvert.PopulateObject 中排除某些基本类型或接口中不存在的属性?
- sql - 如何让 PostgreSQL 给我类似 MySQL SHOW COLUMNS 的结果?
- database - 当字段和值存在时,MongoDB find() 查询不返回任何内容
- html - 如何解决在 HTML 和 CSS 中分离三个并排元素的问题
- lua - Lua Coroutines resume:'resume'的错误参数#-1(预期的布尔值)
- swift - 导航栏第一次没有正确充电
- c# - C# - 哪个接口未注册,如何注册?
- grafana - 即使指标很好,Grafana 也会发出警报