如果我的工作目录是符号链接,os.getcwd()
and 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”?
如果你想使用 os.system(),请使用os.system("/bin/pwd -L")获取当前工作目录的逻辑路径。
如果从 bash shell 运行,只需使用“$PWD”,或者从 python 使用os.environ["PWD"]无需分叉进程os.system().
But 这两个解决方案都假设您位于文件所在的目录中.
基于 Eric H 的界面构建:
import os,subprocess
def abspath(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))
def abspathenv(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"))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)