Python:如果目录是符号链接,则getcwd和pwd给出不同的结果 [英] Python : getcwd and pwd if directory is a symbolic link give different results
问题描述
如果我的工作目录是符号链接,则os.getcwd()
和os.system("pwd")
不会给出相同的结果.我想使用os.path.abspath(".")
故意获取我的工作目录(或其中的文件)的完整路径,而不是获得与os.path.realpath(".")
相同的结果.
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(".")
.
如何在python 2.7中获取类似os.path.abspath(".", followlink=False)
的东西?
How to get, in python 2.7, something like os.path.abspath(".", followlink=False)
?
示例:/tmp是/private/tmp的符号链接
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"
如何从相对路径"toto.txt"中获取"/tmp/toto.txt"?
How can I get "/tmp/toto.txt" from the relative path "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"
这篇关于Python:如果目录是符号链接,则getcwd和pwd给出不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!