如何在 Python 中获取符号链接目标? [英] How to get symlink target in Python?
问题描述
使用 Python,我需要检查数百个符号链接是否正确,如果不正确,则重新创建它们.我现在要做的是比较我想要的和我拥有的真实路径,但它很慢,因为它是通过自动挂载的 NFS.
否则我将使用命令 'ls -l
' 运行一个子进程并处理返回的字符串列表.我更喜欢更好的解决方案,使用 Python 库...
Edit1:我有:link_name ->link_target
然后 link_target ->a_real_file
.我需要的是从 link_name
中提取 link_target
,而不是 a_real_file
.我不在乎真实文件是否存在.
Edit2: 可能是我表达的不对.我所说的正确符号链接是指向预定义路径的链接,即使它不存在".所以我需要检查一下:
link_name_1 ->目标_1link_name_2 ->目标_2
这就是为什么我需要提取目标,而不是真正的路径.然后我将它们与参考(字典)进行比较.所以我的问题是:如何提取目标路径?
os.readlink()
的问题是它只能解决链接的 1 步.我们可能会遇到这样的情况,A
链接到另一个链接 B
,而 B
链接悬空.
$ ln -s/tmp/example/notexist/tmp/example/B$ ln -s/tmp/example/B/tmp/example/A$ ls -l/tmp/示例->/tmp/示例/BB->/tmp/示例/不存在
现在在 Python 中,os.readlink
为您提供第一个目标.
但在大多数情况下,我认为我们对解析路径感兴趣.所以 pathlib
可以在这里提供帮助:
对于较旧的 Python 版本:
<预><代码>>>>os.path.realpath('A')'/tmp/示例/不存在'Using Python, I need to check whether hundreds of symlinks are correct and recreate them when not. What I do now is to compare real paths of what I want and what I have, but it's slow because it's over NFS with an automount.
Otherwise I'm going to run a subprocess with the command 'ls -l
' and work on the list of strings returned. I would prefer a better solution, using a Python library...
Edit1: I have: link_name -> link_target
and then link_target -> a_real_file
. What I need is to extract link_target
from link_name
, not a_real_file
. I don't care if the real file does not exist.
Edit2: Maybe I did not express correctly. What I mean by a correct symlink is 'a link that point to a predefined path, even if it does not exist'. So I need to check that:
link_name_1 -> target_1
link_name_2 -> target_2
That's why I need to extract targets, not the real paths. Then I compare them to a reference (dictionary). So my question is: How do I extract the target path?
The problem with os.readlink()
is it will only resolve 1 step of the link. We can have a situation where A
links to another link B
, and B
link is dangling.
$ ln -s /tmp/example/notexist /tmp/example/B
$ ln -s /tmp/example/B /tmp/example/A
$ ls -l /tmp/example
A -> /tmp/example/B
B -> /tmp/example/notexist
Now in Python, os.readlink
gives you the first target.
>>> import os
>>> os.readlink('A')
'/tmp/example/B'
But in most situations I assume we are interested in the resolved path. So pathlib
can help here:
>>> from pathlib import Path
>>> Path('A').resolve()
PosixPath('/tmp/example/notexist')
For older Python versions:
>>> os.path.realpath('A')
'/tmp/example/notexist'
这篇关于如何在 Python 中获取符号链接目标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!