如果我的工作目录是一个符号链接,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”?
解决方案是:
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"