如何在python中获取/设置逻辑目录路径

Moe*_*Moe 10 python symlink path

在python中,可以获取或设置逻辑目录(而不是绝对目录).

例如,如果我有:

/real/path/to/dir
Run Code Online (Sandbox Code Playgroud)

我有

/linked/path/to/dir
Run Code Online (Sandbox Code Playgroud)

链接到同一目录.

使用os.getcwd和os.chdir将始终使用绝对路径

>>> import os
>>> os.chdir('/linked/path/to/dir')
>>> print os.getcwd()
/real/path/to/dir
Run Code Online (Sandbox Code Playgroud)

我发现解决这个问题的唯一方法是在另一个进程中启动'pwd'并读取输出.但是,这只有在您第一次调用os.chdir之后才有效.

nos*_*klo 13

底层操作系统/ 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.
Run Code Online (Sandbox Code Playgroud)