简体   繁体   English

Python pathlib:解决符号链接的完整路径,而不遵循它

[英]Python pathlib: Resolve full path to symbolic link without following it

Let's say I have a link /home/me/folder/link that points to /home/me/target . 假设我有一个链接/home/me/folder/link指向/home/me/target When I call 我打电话的时候

pathlib.Path("link").resolve()

from /home/me/folder/ , it will return the resolved path to the target , not the resolved path of the link. /home/me/folder/ ,它将返回到目标的已解析路径,而不是已解析的链接路径。 How can I get the latter using pathlib (there don't seem to be any options for resolve() )? 如何使用pathlib获取后者(似乎没有任何resolve()选项)?

(with os.path the equivalent of what I'm looking for would be os.path.abspath("link") ) (使用os.path相当于我正在寻找的是os.path.abspath("link")

pathlib.Path has an absolute method that does what you want. pathlib.Path有一个absolute方法,可以做你想要的。

$  mkdir folder
$  touch target
$  ln -s ~/target ~/folder/link
$  ls -l folder/
total 0
lrwxrwxrwx 1 me users 16 Feb 20 19:47 link -> /home/me/target
$  cd folder

$/folder  python3.7 -c 'import os.path;print(os.path.abspath("link"))'
/home/me/folder/link

$/folder  python3.7 -c 'import pathlib;p = pathlib.Path("link");print(p.absolute())'
/home/me/folder/link

The method doesn't appear in the module documentation, but its docstring reads: 该方法未出现在模块文档中,但其文档字符串显示为:

Return an absolute version of this path. 返回此路径的绝对版本。 This function works even if the path doesn't point to anything. 即使路径没有指向任何内容,此功能也可以工作。 No normalization is done, ie all '.' 没有进行标准化,即所有'。' and '..' will be kept along. 和'..'将保持一致。 Use resolve() to get the canonical path to a file. 使用resolve()获取文件的规范路径。

It's worth noting that there are comments in the method code (in the 3.7 branch) that suggest it may not be fully tested on all platforms. 值得注意的是,方法代码(在3.7分支中)中有注释表明它可能无法在所有平台上进行全面测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM