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" ?
推荐答案
如果要使用 os.system(),请使用 os.system("/bin/pwd -L")获取当前工作目录的逻辑路径.
If you want to use os.system(), use os.system("/bin/pwd -L") to get the logical path for the current working directory.
如果从 bash shell 运行,只需使用$PWD",或者从 python 运行os.environ[PWD"],而无需使用 os.system 分叉进程().
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().
但是这两种解决方案都假设您位于文件所在的目录中.
基于 Eric H 的界面构建:
Building on the interface from 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"))
这篇关于Python:如果目录是符号链接,则 getcwd 和 pwd 给出不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!