2016-08-24 1103 views
16

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

+1

'__file__'適用於*模塊和Python腳本*,而不是筆記本電腦。你找到的答案在這裏不適用。 –

+3

[如何獲取當前的IPython Notebook名稱](http://stackoverflow.com/q/12544056)看起來更相關? –

回答

3

這是不可能得到的路徑筆記本。您可能會找到一種方法來獲取它只能在一個環境中工作(例如os.getcwd()),但如果以不同方式加載筆記本計算機,則不一定有效。

相反,嘗試寫筆記本,以便它不需要知道自己的路徑。如果做了像獲得密碼那樣的事情,那麼一定要快速失敗/如果這不起作用,則打印一個錯誤,而不要默默地嘗試繼續。

參見:https://github.com/ipython/ipython/issues/10123