import os
def isLink(a, b):
return os.path.islink(a) and os.path.realpath(a) == os.path.realpath(b)
Note that this resolves the second argument to a real path. So it will return True if 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 change
os.path.realpath(a) == os.path.realpath(b)
to
os.path.realpath(a) == os.path.abspath(b)
Now if 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.
For example,
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
os.path.realpath()
. – Administer