如何获取 Jupyter Notebook 的路径? [英] How to obtain Jupyter Notebook's path?

查看:91
本文介绍了如何获取 Jupyter Notebook 的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有获取笔记本路径的函数?

Is there a function to obtain a Notebook's path?

我在谷歌上搜索了一些关于这个主题的信息,但没有找到一个简单的方法......我想获得笔记本的路径,以便我可以在其他地方使用它.这样我就可以在与笔记本相同的路径中保存/使用文件,而不必担心保存在哪里.

I've Googled a little on the subject but didn't find a simple way to do it... I want to obtain the Notebook's path so I can then use it elsewhere. This way I could save/use files in the same path as the notebook without worrying about where it got saved.

现在我的解决方案是将以下代码放在最上面,但显然这至少会带来必须手动执行单元格的问题,而且如果工作目录发生更改,这将停止工作.

Right now my solution is to put the following code on top but obviously this poses at least the problem of manually having to execute a cell and also if the working directory changes this will stop working.

import os
current_path = os.getcwd()

推荐答案

TLDR:你不能

无法始终如一地获取 Jupyter 笔记本的路径.有关详细信息,请参阅 ipython 问题 #10123.我会引用Carreau:

以下是内核(在本例中为 IPython)的一些原因:

Here are some reasons why the kernel (in this case IPython):

  • 可能无法从单个文件运行
  • 即使是一个文件,该文件也可能不是笔记本.
  • 即使是 notebook,它也可能不在文件系统上.
  • 即使在一个文件系统上,它也可能不在同一台机器上.
  • 即使在同一台机器上,文件的路径在 IPython 上下文中也可能没有意义.
  • 即使有道理,Jupyter 协议的设计也并非如此.我们没有计划在短期或长期内改变这种抽象.

您的 hack 在大多数情况下都有效,并且根据情况还不错.

Your hack works in most cases and is not too bad depending on the situation.

这篇关于如何获取 Jupyter Notebook 的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆