简体   繁体   English

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

[英]How to get/set logical directory path in python

In python is it possible to get or set a logical directory (as opposed to an absolute one). 在python中,可以获取或设置逻辑目录(而不是绝对目录)。

For example if I have: 例如,如果我有:

/real/path/to/dir

and I have 我有

/linked/path/to/dir

linked to the same directory. 链接到同一目录。

using os.getcwd and os.chdir will always use the absolute path 使用os.getcwd和os.chdir将始终使用绝对路径

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

The only way I have found to get around this at all is to launch 'pwd' in another process and read the output. 我发现解决这个问题的唯一方法是在另一个进程中启动'pwd'并读取输出。 However, this only works until you call os.chdir for the first time. 但是,这只有在您第一次调用os.chdir之后才有效。

The underlying operational system / shell reports real paths to python. 底层操作系统/ shell报告了python的真实路径。

So, there really is no way around it, since os.getcwd() is a wrapped call to C Library getcwd() function. 因此,实际上没有办法解决它,因为os.getcwd()是对C库getcwd()函数的包装调用。

There are some workarounds in the spirit of the one that you already know which is launching pwd . 有一些你已经知道的推出pwd精神的解决方法。

Another one would involve using os.environ['PWD'] . 另一个涉及使用os.environ['PWD'] If that environmnent variable is set you can make some getcwd function that respects it. 如果设置了environmnent变量,则可以创建一个尊重它的getcwd函数。

The solution below combines both: 以下解决方案结合了两者:

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.

This also does the trick for me: 这对我来说也很有用:

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

Here is a demonstration in python shell: 这是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'

Getting the environment variable PWD didn't always work for me so I use the popen method. 获取环境变量PWD并不总是适合我,所以我使用popen方法。 Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM