我在使用Python 3.4.2和 的Jupyter Notebook服务器(v4.2.2)我想使用全局名称__file__
,因为笔记本将从其他用户克隆,并在一个节我要运行:__file__不存在于Jupyter笔记本
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
。
,但我得到
NameError: name
'__file__'
is not defined
我搜索了这个错误在网上发现了“解决方案”,我应该更好地利用sys.argv[0]
,但print(sys.argv[0])
回报
/usr/local/lib/python3.4/dist-packages/ipykernel/__main__.py
但正确的笔记本电脑的位置误差应该是/home/ubuntu/notebooks/
。
感谢参考How do I get the current IPython Notebook name从马亭皮特斯(评论)最后的答案(不接受)适合适合我的需求:
print(os.getcwd())
/home/ubuntu/notebooks
'__file__'适用于*模块和Python脚本*,而不是笔记本电脑。你找到的答案在这里不适用。 –
[如何获取当前的IPython Notebook名称](http://stackoverflow.com/q/12544056)看起来更相关? –