簡體   English   中英

如何在python中獲取/設置邏輯目錄路徑

[英]How to get/set logical directory path in 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之后才有效。

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

因此,實際上沒有辦法解決它,因為os.getcwd()是對C庫getcwd()函數的包裝調用。

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

另一個涉及使用os.environ['PWD'] 如果設置了environmnent變量,則可以創建一個尊重它的getcwd函數。

以下解決方案結合了兩者:

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.

這對我來說也很有用:

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方法。 干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM