Python : Getcwd And Pwd If Directory Is A Symbolic Link Give Different Results
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 workin
Solution 1:
If you want to use os.system(), use os.system("/bin/pwd -L") to get the logical path for the current working directory.
If running from a bash shell just use "$PWD", or from python use os.environ["PWD"] without having to fork a process with os.system().
But both of these solutions assume you're in the directory where the file is.
Building on the interface from Eric H:
import os,subprocess
defabspath(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))
defabspathenv(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"))
Solution 2:
A solution is :
from subprocess import Popen, PIPE
defabspath(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"
Post a Comment for "Python : Getcwd And Pwd If Directory Is A Symbolic Link Give Different Results"