jupyter笔记本可以找到自己的文件名吗? [英] Can a jupyter notebook find its own filename?
问题描述
jupyter笔记本是否有可能获得自己的文件名,这与我们从python脚本执行的操作类似?
Is it possible for a jupyter notebook to get the name of its own file, similarly to what we would do from a python script?
os.path.basename(__file__)
似乎不起作用,至少对于jupyterlab上的我而言
os.path.basename(__file__)
doesn't seem to work, at least for me on jupyterlab
sys.argv[0]
返回my_home/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py
推荐答案
我发现的唯一方法是通过JavaScritp,如下所示 此答案.
The only way I've found is through JavaScritp as in this answer.
紧凑形式是一个像这样的单元格:
The compact form is a cell like this:
%%javascript
IPython.notebook.kernel.execute(`notebookName = '${window.document.getElementById("notebook_name").innerHTML}'`);
之后,您将获得变量notebookName
,其名称显示在
页面顶部.
after that you'll have the variable notebookName
with the name that appears at the
top of the page.
更好的解决方案可能是使用IPython.notebook.notebook_name
:
A better solution may be using IPython.notebook.notebook_name
:
%%javascript
IPython.notebook.kernel.execute(`notebookName = '${IPython.notebook.notebook_name}'`);
它为您提供扩展名.ipynb
这篇关于jupyter笔记本可以找到自己的文件名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!