我在 Jupyter Notebook 服務器 (v4.2.2) 上使用 Python 3.4 .2 並且我想使用全局名稱 __file__
,因為筆記本將從其他用戶那里克隆,並且在一個部分中我必須運行:
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
I搜索 網上這個錯誤,找到了我最好使用sys.argv[0]
的“解決方案”,但是print(sys.argv[0])
返回
/usr/local/lib/python3.4/dist-packages/ipykernel/__main__.py
但是正確的筆記本位置應該是 /home/ubuntu/notebooks/
。
感謝您的參考 如何從 Martijn Pieters 獲取當前的 IPython Notebook 名稱(評論)最後一個答案(不接受)非常適合我需要:
print(os.getcwd())
/home/ubuntu/notebooks