2011-07-28 29 views
4
import os 
print __file__ 
print os.path.dirname(__file__) 
os.chdir('/tmp') 
print __file__ # unchanged, of course 
print os.path.dirname(__file__) # now broken 

我有上面的這個問題,dirname(__file__)不能再依賴os.chdir已經在腳本中使用後,模塊加載程序已設置__file__後。__file__和os.path模塊不能很好地播放?

解決此問題的常用機制是什麼?假設您可能不知道以前可能調用os.chdir的位置/時間/方式?

編輯:我希望這第二個例子可以更好地闡明我的問題

import os 
old_dir = os.getcwd() 
print os.path.abspath(__file__) 
os.chdir('/tmp') 
print os.path.abspath(__file__) 
os.chdir(old_dir) 

輸出是這樣的:

[email protected]:~$ python --version 
Python 2.7.1+ 
[email protected]:~$ pwd 
/home/wim 
[email protected]:~$ python /home/wim/spam.py 
/home/wim/spam.py 
/home/wim/spam.py 
[email protected]:~$ python ./spam.py 
/home/wim/spam.py 
/tmp/spam.py 
+0

無法在Windows 7,Python 2.6.2上重現。目錄是否切換至關鍵位置,或者是否有任何目錄執行此操作?必須導入文件,還是可以單獨運行?你使用的是什麼Python版本?究竟是如何第二次「破」(有什麼不是預期的)? – Cameron

+0

「解決此問題的常用機制是什麼?」?什麼?你爲什麼要'__file__'的絕對路徑?爲什麼你要等到你做了「不知道os.chdir以前被調用的地方/時間/地點」才能獲得絕對路徑? –

+0

對不起,原因是在調試幫助函數中使用。我使用inspect模塊來獲得一堆其他信息,例如,我可以使用dbgp('i')'而不是亂丟''print i''代碼,並得到不同顏色的輸出行,例如' /abs/path/to_file.py:line_number我= repr(i)' – wim

回答

1

__file__必須存在於某處sys.path

for dirname in sys.path: 
    if os.path.exists(os.path.join(dirname,__file__)): 
     # The directory name for `__file__` was dirname 
+0

不能在文件名中相同'__file__'多次存在於'sys.path'中? – wim

+0

@wim:是的。它可以。所以? Python在加載時按順序搜索sys.path。您正在以相同的順序搜索。 –

+0

這大部分是正確的。然而,'__file__'是一個絕對路徑,'os.path.exists(dirname,__ file __)'返回True是因爲'sys.path [0]'中的'dirname'是''' '(空串)。 – wim

1

最後一個例子已在__file__名稱(./xxx.py)的相對路徑元件。當調用abspath時,它將擴展到當前目錄。

如果你把這個代碼放在一個模塊中,你就不會有這個問題。

相關問題