听起来很简单,如何从笔记本中的单元格获取保存路径(.ipynb 文件的位置)?
问问题
9947 次
3 回答
1
事实证明,可以使用一些 javascript 魔法从笔记本页面的 HTML 正文中的某些属性中获取笔记本路径:
%%javascript
var kernel = IPython.notebook.kernel;
var proj = window.document.body.getAttribute('data-project');
var path = window.document.body.getAttribute('data-notebook-path');
var command = "proj = " + "'"+proj+"'";
kernel.execute(command);
var command = "path = " + "'"+path+"'" kernel.execute(command)
在单元格中执行上述操作后,可以通过以下方式获取路径
import os
os.path.join( proj, path)
于 2015-03-23T04:59:11.120 回答
1
使用 Jupyter,您可以通过以下方式在 URL 中获取笔记本的相对路径:
%%javascript
var kernel = Jupyter.notebook.kernel;
var command = ["notebookPath = ",
"'", window.document.body.dataset.notebookPath, "'" ].join('')
//alert(command)
kernel.execute(command)
var command = ["notebookName = ",
"'", window.document.body.dataset.notebookName, "'" ].join('')
//alert(command)
kernel.execute(command)
然后你可以检查 python 变量 notebookName 和 notebookPath
我不确定 url 前缀的结果,以及当您已经更改笔记本中的当前目录时如何处理这种情况
于 2016-02-22T12:08:32.763 回答
0
其他答案没有得到正确的完整路径。他们要么相对于内核的笔记本工作目录或 Jupyter 主目录获取它。
以下是获取完整笔记本路径的方法:
首先,使用 JavaScript 单元格获取笔记本文件名,对其进行 URL 解码并将其放入 Python 变量中:
%%javascript
// Fetch and decode the notebook filename
var notebookFilename = decodeURIComponent(
window.document.body.dataset.notebookName
);
// Drop the filename into a Python variable
Jupyter.notebook.kernel.execute(
`notebook_filename = "${notebookFilename}"`
);
然后在第二个单元格中,将该文件名转换为绝对路径:
import os
notebook_path = os.path.abspath(notebook_filename)
notebook_path
notebook_path
现在将是笔记本的完整绝对路径。
使用 jupyter-notebook 5.7.8 在 Ubuntu 上的 Chrome 77 上测试
于 2019-11-21T17:51:37.123 回答