【问题标题】:Can a jupyter notebook find its own filename?jupyter notebook 可以找到自己的文件名吗?
【发布时间】:2019-03-12 11:41:35
【问题描述】:

jupyter notebook 是否有可能获取自己文件的名称,类似于我们从 python 脚本中所做的事情?

os.path.basename(__file__) 似乎不起作用,至少对 jupyterlab 上的我来说是这样

sys.argv[0] 返回my_home/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py

【问题讨论】:

  • 您是否尝试过按照this answer 中的建议进行操作?
  • 我没有看到,但是当我尝试时,我得到了Javascript Error: IPython is not defined
  • 它对我来说很好用。我只是用我拥有的一个随机笔记本对其进行了测试。我不确定该错误的原因是什么。
  • 我在 jupyter notebook 中试过(我在 jupyter 实验室),我没有得到同样的错误,我可以得到文件名(这是我问的),但我不能得到完整的路径。
  • 我不确定您将如何获得完整路径,或者是否有可能。我确实看到其他人在其他帖子上发表了相同的评论,但也许其他人对如何做到这一点有所了解。

标签: python jupyter-notebook jupyter-lab python-os


【解决方案1】:

我发现的唯一方法是通过 JavaScritp,如 this answer.

紧凑形式是这样的单元格:

%%javascript
IPython.notebook.kernel.execute(`notebookName = '${window.document.getElementById("notebook_name").innerHTML}'`);

之后,您将拥有变量 notebookName,其名称显示在 页面顶部。

更好的解决方案可能是使用IPython.notebook.notebook_name:

%%javascript
IPython.notebook.kernel.execute(`notebookName = '${IPython.notebook.notebook_name}'`);

它会为您提供扩展名为 .ipynb 的名称

【讨论】:

  • 在 jupyter 实验室我收到错误 Javascript Error: IPython is not defined
  • 太棒了!
  • 是的,Javascript Error: IPython is not defined jupyter lab : 3.0.14jupyter core : 4.7.1
猜你喜欢
  • 2010-12-24
  • 2010-09-05
  • 2012-02-06
  • 1970-01-01
  • 2016-03-30
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多