__file__ 在 Jupyter Notebook 中不存在 [英] __file__ does not exist in Jupyter Notebook

查看:127
本文介绍了__file__ 在 Jupyter Notebook 中不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 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 and I 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.

但我收到错误

NameError: name '__file__' 未定义

NameError: name '__file__' is not defined

我在网上搜索了这个错误,找到了我最好使用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

/usr/local/lib/python3.4/dist-packages/ipykernel/__main__.py

但正确的笔记本位置应该是/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())

/home/ubuntu/notebooks

/home/ubuntu/notebooks

推荐答案

如果您想获取运行脚本的目录的路径,我强烈建议您使用,

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 的路径库

请注意,__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 中不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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