问题描述
我正在使用Python 3.4的 Jupyter Notebook 服务器(v4.2.2) .2和我想使用全局名称__file__
,因为笔记本将从其他用户那里克隆而我必须在一个部分中运行:
I'm on a Jupyter Notebook server (v4.2.2) with Python 3.4.2 andI want to use the global name __file__
, because the notebook will be cloned from other users and in one section I have to run:
def __init__(self, trainingSamplesFolder='samples', maskFolder='masks'):
self.trainingSamplesFolder = self.__getAbsPath(trainingSamplesFolder)
self.maskFolder = self.__getAbsPath(maskFolder)
def __getAbsPath(self, path):
if os.path.isabs(path):
return path
else:
return os.path.join(os.path.dirname(__file__), path)
__getAbsPath(self, path)
检查path
参数是相对路径还是绝对路径,并返回path
的绝对版本.因此,我以后可以安全地使用返回的path
.
The __getAbsPath(self, path)
checks if a path
param is a relative or absolute path and returns the absolute version of path
. So I can use the returned path
safely later.
但是我得到了错误
我在线搜索了此错误,发现我最好使用sys.argv[0]
的解决方案",但print(sys.argv[0])
返回
I searched for this error online and found the "solution" that I should better use sys.argv[0]
, but print(sys.argv[0])
returns
但是笔记本的正确位置应该是/home/ubuntu/notebooks/
.
But the correct notebook location should be /home/ubuntu/notebooks/
.
感谢参考 如何获取Martijn Pieters提供的当前IPython Notebook名称 (评论),最后一个答案(未接受)非常适合我的需求:
Thanks for the reference How do I get the current IPython Notebook name from Martijn Pieters (comments) the last answer (not accepted) fits perfect for my needs:
print(os.getcwd())
推荐答案
如果要获取运行脚本的目录的路径,强烈建议使用
If you want to get path of the directory in which your script is running, I would highly recommend using,
os.path.abspath('')
优势
- 它在Jupyter Notebook中工作
- 它是REPL的作品
- 它不需要Python 3.4的pathlib
请注意,__file__
具有优势的一种情况是,当您从目录A调用python但在目录B中运行脚本时.在这种情况下,上述方法以及大多数其他方法将返回A,而不是B.但是对于Jupyter notbook,您始终会获得.ipyn
文件的文件夹,而不是启动jupyter notebook
的目录.
Please note that one scenario where __file__
has advantage is when you are invoking python from directory A but running script in directory B. In that case above as well as most other methods will return A, not B. However for Jupyter notbook, you always get folder for .ipyn
file instead of the directory from where you launched jupyter notebook
.
这篇关于__file__在Jupyter Notebook中不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!