我在使用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)看起來更相關? –