问题
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