【问题标题】:Python : getcwd and pwd if directory is a symbolic link give different resultsPython:如果目录是符号链接,则 getcwd 和 pwd 给出不同的结果
【发布时间】:2019-07-06 23:37:19
【问题描述】:

如果我的工作目录是符号链接,os.getcwd()os.system("pwd") 不会给出相同的结果。我想使用os.path.abspath(".") 来获取我的工作目录(或其中的文件)的完整路径,目的是为了获得与os.path.realpath(".") 相同的结果。

如何在 python 2.7 中获得类似 os.path.abspath(".", followlink=False) 的东西?

示例:/tmp 是指向 /private/tmp 的符号链接

cd /tmp
touch toto.txt
python
print os.path.abspath("toto.txt")
--> "/private/tmp/toto.txt"
os.system("pwd")
--> "/tmp"
os.getcwd()
--> "/private/tmp"

如何从相对路径“toto.txt”中获取“/tmp/toto.txt”?

【问题讨论】:

    标签: python directory path absolute


    【解决方案1】:

    如果要使用 os.system(),请使用 os.system("/bin/pwd -L") 获取当前工作目录的逻辑路径。

    如果从 bash shell 运行,只需使用 "$PWD",或者从 python 使用 os.environ["PWD"] 而无需使用 os.system() 派生进程

    但是这两种解决方案都假定您位于文件所在的目录中

    以 Eric H 的界面为基础:

    import os,subprocess
    def abspath(pathname):
        '''Return logical path (not physical) for pathname using Popen'''
        if pathname[0]=="/":
            return pathname
        lpwd = subprocess.Popen(["/bin/pwd","-L"],stdout=subprocess.PIPE, shell=True).communicate()[0].strip()
        return(os.path.join(lpwd,pathname))
    
    def abspathenv(pathname):
        '''Return logical path (not physical) for pathname using bash $PWD'''
        if pathname[0]=="/":
            return pathname
        return(os.path.join(os.environ["PWD"],pathname))
    
    print(abspath("foo.txt"))
    print(abspathenv("foo.txt"))
    

    【讨论】:

    • pwd 使用环境。 PWD 变量,所以 -L 是我的 shell 上的默认选项。无论如何,使用 -L 是一种安全性。
    • 是的,内置的 shell "pwd" 可能使用 $PWD,但 GNU 核心实用程序 "/bin/pwd" 没有,这是使用 subprocess.Popen 或 os.system() 的初衷,我已经更新了答案
    【解决方案2】:

    解决办法是:

    from subprocess import Popen, PIPE
    
    def abspath(pathname):
        """ Returns absolute path not following symbolic links. """
        if pathname[0]=="/":
            return pathname
        # current working directory
        cwd = Popen("pwd", stdout=PIPE, shell=True).communicate()[0].strip()
        return os.path.join(cwd, pathname)
    
    print os.path.abspath("toto.txt")  # --> "/private/tmp/toto.txt"
    print abspath("toto.txt")          # --> "/tmp/toto.txt"
    

    【讨论】:

    • 我认为您需要确保默认情况下调用的“pwd”不会跟随符号链接,使用“pwd -L”应该可以做到。
    猜你喜欢
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多