2008-09-23 45 views
7

在python中可以獲取或設置邏輯目錄(而不是絕對目錄)。如何在python中獲取/設置邏輯目錄路徑

例如,如果我有:

/real/path/to/dir 

,我有

/linked/path/to/dir 

鏈接到同一目錄下。使用os.getcwd和os.chdir將始終使用絕對路徑

>>> import os 
>>> os.chdir('/linked/path/to/dir') 
>>> print os.getcwd() 
/real/path/to/dir 

我已經找到了解決這個問題在所有的唯一途徑

是在另一個進程中推出「PWD」和讀取輸出。但是,這隻有在您第一次調用os.chdir時纔有效。

回答

11

底層操作系統/ shell報告python的真實路徑。

所以,真的沒有辦法解決它,因爲os.getcwd()是C庫getcwd()功能的封裝調用。

有一些你已經知道啓動pwd的精神的一些解決方法。

另一個涉及使用os.environ['PWD']。如果該環境變量已設置,則可以創建一些尊重該變量的函數。

該解決方案如下結合了:

import os 
from subprocess import Popen, PIPE 

class CwdKeeper(object): 
    def __init__(self): 
     self._cwd = os.environ.get("PWD") 
     if self._cwd is None: # no environment. fall back to calling pwd on shell 
      self._cwd = Popen('pwd', stdout=PIPE).communicate()[0].strip() 
     self._os_getcwd = os.getcwd 
     self._os_chdir = os.chdir 

    def chdir(self, path): 
     if not self._cwd: 
      return self._os_chdir(path) 
     p = os.path.normpath(os.path.join(self._cwd, path)) 
     result = self._os_chdir(p) 
     self._cwd = p 
     os.environ["PWD"] = p 
     return result 

    def getcwd(self): 
     if not self._cwd: 
      return self._os_getcwd() 
     return self._cwd 

cwd = CwdKeeper() 
print cwd.getcwd() 
# use only cwd.chdir and cwd.getcwd from now on.  
# monkeypatch os if you want: 
os.chdir = cwd.chdir 
os.getcwd = cwd.getcwd 
# now you can use os.chdir and os.getcwd as normal. 
+0

謝謝! getcwd()需要一個自我論證 - 除了它完美的工作! – Moe 2008-09-23 21:50:47

1

這也不會把戲對我來說:

import os 
os.popen('pwd').read().strip('\n') 

這裏是在Python Shell演示:

>>> import os 
>>> os.popen('pwd').read() 
'/home/projteam/staging/site/proj\n' 
>>> os.popen('pwd').read().strip('\n') 
'/home/projteam/staging/site/proj' 
>>> # Also works if PWD env var is set 
>>> os.getenv('PWD') 
'/home/projteam/staging/site/proj' 
>>> # This gets actual path, not symlinked path 
>>> import subprocess 
>>> p = subprocess.Popen('pwd', stdout=subprocess.PIPE) 
>>> p.communicate()[0] # returns non-symlink path 
'/home/projteam/staging/deploys/20150114-141114/site/proj\n' 

獲取環境可變的PWD並不總是爲我工作,所以我使用popen方法。乾杯!