Python : getcwd and pwd if directory is a symbolic link give different results

一个人想着一个人 提交于 2020-06-16 19:32:51

问题


If my working directory is a symbolic link, os.getcwd() and os.system("pwd") do not give the same result. I would like to use os.path.abspath(".") to get the full path of my working directory (or a file in it), on purpose, not to get the same result than os.path.realpath(".").

How to get, in python 2.7, something like os.path.abspath(".", followlink=False) ?

Example : /tmp is a symbolic link to /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"

How can I get "/tmp/toto.txt" from the relative path "toto.txt" ?


回答1:


A solution is :

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"


来源:https://stackoverflow.com/questions/54665065/python-getcwd-and-pwd-if-directory-is-a-symbolic-link-give-different-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!