如何获取正在使用的ipython笔记本的文件路径? (相当于__file__) [英] how to get the file path for the ipython notebook in use? (the equivalent to __file__)
问题描述
我想将目录更改为jupyter笔记本的父目录.
I want to change dir to the parent dir of my jupyter notebook.
由于未定义__file__
,因此我无法使用os.path.basename(os.path.dirname(os.path.realpath(__file__)))
进入笔记本路径.
I can not take the notebook path using os.path.basename(os.path.dirname(os.path.realpath(__file__)))
as __file__
is not defined.
如何获取我正在使用的ipynb文件的目录,以便对其进行os.chdir()?
How can I get the dir of the ipynb file I am using in order to os.chdir() to it?
推荐答案
您不能
https://github.com/ipython/ipython/issues/10123
原因是因为您始终在内核中运行,并且从理论上讲,多个笔记本可以连接到该内核.
The reason is because you're always running in the kernel, and in theory multiple notebooks could connect to that kernel.
但是-默认情况下,如果要启动笔记本,则将当前工作目录设置为笔记本的路径.因此,最接近的是调用os.getcwd()
However - by default if you're starting a notebook, the current working directory is set to the path of the notebook. So the closest, is to call os.getcwd()
我刚刚创建了最无聊的发布的笔记本示例来演示这一点,您可以看到,此笔记本反映了它的路径,并且位于子目录中的该目录也反映了正确的路径
I just created the most boring published notebook example to demonstrate this, you can see that, this notebook reflects it's path, and this one that's in a subdirectory also reflects the proper path
这篇关于如何获取正在使用的ipython笔记本的文件路径? (相当于__file__)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!