如果路径符号链接到另一个路径 [英] If path is symlink to another path
问题描述
/ home / user / x
符号链接到 / home / user / z
,但<$ c $ >>>打印(isLink(/ home / user / x,/ home / user / z))
True
>>> print(isLink(/ home / user / y, / home / user / z))
False
>>> print(isLink(/ home / user / z,/ home / user / z))
$ False
$ b
解决方案
import os
def isLink(a,b):
(b)
请注意,这会将第二个参数解析为真实路径。所以如果 a
和 b
都是符号链接,那么它将返回True,只要它们都指向相同的实际路径。如果您不希望将 b
解析为实际路径,请更改
os.path.realpath(a)== os.path.realpath(b)
os.path.realpath(a)== os.path.abspath code>
现在如果 a
指向 b 和 b
指向 c
,并且您希望 isLink ,b)
仍然是真的,那么你会希望使用 os.readlink(a)
而不是 os (b):
$ $ $ $ b返回os.path.islink(a)和os.path.abspath(os.readlink(a))== os.path.abspath(b)
例如, Is there a way in Python to check whether or not a file is a symlink to another specific file? For example, if (/home/user/z is the original file, not a symlink) Note that this resolves the second argument to a real path. So it will return True if to Now if For example,
这篇关于如果路径符号链接到另一个路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! os.readlink(a)
的计算结果为 b
a
指向,而 os.path.realpath(a)
评估至 c
, 指向
$ b
In [129]:!touch z
In [130]:!ln -szx
In在[132]中:!ln -swy
在[138]中:isLink('x','z')
[138]:True
在[139]中:isLink('y','z')
Out [139]:False
In [ 140]:isLink('z','z')
Out [140]:False
/home/user/x
symlinks to /home/user/z
, but /home/user/y
links somewhere else:>>>print(isLink("/home/user/x", "/home/user/z"))
True
>>>print(isLink("/home/user/y", "/home/user/z"))
False
>>>print(isLink("/home/user/z", "/home/user/z"))
False
import os
def isLink(a, b):
return os.path.islink(a) and os.path.realpath(a) == os.path.realpath(b)
a
and b
are both symlinks, as long as they both point to the same real path. If you don't want b
to be resolved to a real path, then changeos.path.realpath(a) == os.path.realpath(b)
os.path.realpath(a) == os.path.abspath(b)
a
points to b
, and b
points to c
, and you want isLink(a, b)
to still be True, then you'll want to use os.readlink(a)
instead of os.path.realpath(a)
:def isLink(a, b):
return os.path.islink(a) and os.path.abspath(os.readlink(a)) == os.path.abspath(b)
os.readlink(a)
evaluates to b
, the next link that a
points to, whereas os.path.realpath(a)
evaluates to c
, the final path that a
points to.
In [129]: !touch z
In [130]: !ln -s z x
In [131]: !touch w
In [132]: !ln -s w y
In [138]: isLink('x', 'z')
Out[138]: True
In [139]: isLink('y', 'z')
Out[139]: False
In [140]: isLink('z', 'z')
Out[140]: False