Python:getcwd和pwd如果目录是一个符号链接给出不同的结果

问题描述 投票:0回答:1

如果我的工作目录是一个符号链接,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 hyperlink path directory absolute
1个回答
0
投票

解决方案是:

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"
© www.soinside.com 2019 - 2024. All rights reserved.